iOS 开发新手。所以我传递了一个带有对象地址的方法,认为这样做会改变同一个对象:
_posts = [[NSMutableArray alloc]init];
FetchPosts *dataControl = [[FetchPosts alloc]init];
[dataControl accessPosts: _posts];
下面的代码接收传入的对象。
-(void)accessPosts: (NSMutableArray *)transition {
//access the posts here.
_readablePosts = transition;
NSURL *url = [NSURL URLWithString: @"private"];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
_jsonPosts = [[NSMutableData alloc]init];
[_jsonPosts appendData: data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_jsonPosts options:NSJSONReadingAllowFragments error:&error];
for(int i = 0; i<jsonArray.count; i++) {
NSDictionary *element = jsonArray[i];
Posts *newPost = [[Posts alloc]init];
newPost.title = element[@"Title"];
newPost.discovery = element[@"Discovery"];
newPost.summary = element[@"Description"];
newPost.contact = element[@"Contact"];
[_readablePosts addObject:newPost];
}
}
在我看来,一切似乎都已就位。然而,当我返回到我原来的方法时,_posts 并没有像它应该的那样保存正确的对象。我在这里的指针有问题吗?
最佳答案
你调用这个方法-
[dataControl accessPosts: _posts];
调用
[NSURLConnection connectionWithRequest:request delegate:self];
这是一个非阻塞方法,因此它会立即返回并在检索到要处理的数据后调用委托(delegate)方法。
如果您在 accessPosts
返回时立即访问 _posts
,您将在从网络检索数据之前执行此操作。
只有在 connectionDidFinishLoading:
被调用后,您才能访问 _posts
中的数据
一种解决方案是使用委托(delegate)模式。您的外部代码会将自己设置为 FetchPosts
对象的委托(delegate),并从 connectionDidFinishLoading
调用委托(delegate)方法。这不仅可以解决您的异步问题,还可以避免 NSMutableArray
的潜在不安全更新,并避免使用副作用。
您需要在 FetchPosts.h
中创建一个适当的协议(protocol),然后您可以使用类似 -
-(void) requestPosts {
FetchPosts *dataControl = [[FetchPosts alloc]init];
dataControl.delegate=self;
[dataControl accessPosts];
}
-(void) didReceiveNewPosts:(NSArray *)posts {
// Do something with posts
}
FetchPosts.m
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_jsonPosts options:NSJSONReadingAllowFragments error:&error];
for(int i = 0; i<jsonArray.count; i++) {
NSDictionary *element = jsonArray[i];
Posts *newPost = [[Posts alloc]init];
newPost.title = element[@"Title"];
newPost.discovery = element[@"Discovery"];
newPost.summary = element[@"Description"];
newPost.contact = element[@"Contact"];
[_readablePosts addObject:newPost];
}
if ([self.delegate respondsToSelector:@selector(didReceiveNewPosts:)]) {
[self.delegate didReceiveNewPosts:_readablePosts];
}
}
关于ios - 通过引用传递的对象不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30272716/