我有一个正在处理的项目,它有许多不同的新闻提要和公告板,显示来自各种来源的帖子。目前,对于显示提要的视图,我在每个类文件中包含的方法中都有类似、删除和标记按钮的代码。我一直在尝试制作一个实用程序类,它允许我将上面列出的三个功能的代码放在一个对象中,以便在整个项目中使用。我在 C++ 或 Java 中做了完全相同类型的事情,但是在 Objective-c 中重现它时遇到了问题。点赞、删除和标记按钮使用 NSURL 库与 Web 服务交互。Bellow 是我尝试在实用程序类中实现的方法之一的示例,并且是用于在类似按钮中实现的代码:
+ (void)btnLikeAction:(UIButton *)btnLike userIdString:(NSString *)userId contentSource:(NSString *)sourceId cellUsed:(NewsfeedCell *)cell dataForCell:(Post *)post
{
BOOL hasLiked = post.hasLiked;
UILabel *likeLabel = cell.likeCount;
NSString *pId = post.postId;
if (hasLiked)
{
[btnLike setEnabled:NO];
NSString *url = [NSString stringWithFormat: @"http://192.155.94.183/api/v1/likes/unlike/%@/%@/%@/", sourceId, pId, userId];
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
int localCount = [likeLabel.text intValue];
localCount--;
likeLabel.text = [NSString stringWithFormat:@"%i", localCount];
post.likeCount = [NSString stringWithFormat:@"%i", localCount];
post.hasLiked = NO;
[btnLike setEnabled:YES];
}
else
{
[btnLike setEnabled:NO];
NSError *err = nil;
NSDictionary *likeData = [NSDictionary dictionaryWithObjectsAndKeys:
userId, @"user_id",
pId, @"source_id",
sourceId, @"source",
nil];
NSData *JSONLike = [NSJSONSerialization dataWithJSONObject:likeData options:NSJSONWritingPrettyPrinted error:&err];
NSString *url = @"http://192.155.94.183/api/v1/likes.json";
NSURL *URL = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [JSONLike length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:JSONLike];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
int localCount = [likeLabel.text intValue];
localCount++;
likeLabel.text = [NSString stringWithFormat:@"%i", localCount];
post.likeCount = [NSString stringWithFormat:@"%i", localCount];
post.hasLiked = YES;
[btnLike setEnabled:YES];
}
}
此代码使用 Web 服务来更新特定内容的点赞数。当方法被放入单独的 ViewController 类文件时它可以工作,但是当我尝试使用单独的方法创建一个实用程序类时,我遇到了,didReceiveAuthenticationChallenge
和方法没有被调用的问题。最初,我假设委托方法将在调用实用程序方法的文件中调用。但事实并非如此。当我在实际的实用程序类中实现方法定义时,仍然没有调用这些方法。我对该主题进行了一些研究并查看了这篇文章didReceiveResponse
didReceiveData
connectionDidFinishLoading
但发现我无法找到对我的具体情况有所帮助的大量资源。如何设置我的实用程序类?如果需要,我可以发布该实用程序的完整代码。