3

我正在创建一个启用了 ARC 的 iPhone 应用程序,在这种情况下我遇到了这种情况。

在应用程序的每个页面中,都会发生 Web 服务调用。在这种方法中,我在从服务器添加新值之前从数组中删除所有对象。一切正常,但有时应用程序在[self.myArray removeAllObjects].

我为 myArray 设置了@property@property (strong, nonatomic) NSMutableArray myArray;

我在想的是,当我使用 ARC 时,对象 ,myArray在某个时候被释放,我尝试从同一个数组中删除所有对象。这导致崩溃,我不确定,但我没有看到任何其他原因。

因此,我正在考虑在删除其中的对象之前检查数组是否有效。我写了一个示例代码来检查不同的场景。这里是:

NSMutableArray *testArray = [[NSMutableArray alloc]initWithObjects:@"1", @"2", @"3", @"4", nil];

if (testArray) {
    NSLog(@"i am alive");
}

[testArray release];

if (testArray) { //here how to check whether this array is valid or not?
    NSLog(@"i am alive: %@", testArray);
}else{
    NSLog(@"I am dead");
    testArray = [[NSMutableArray alloc]initWithObjects:@"5", @"6", @"7", @"8", nil];
}

[testArray release];
[testArray removeAllObjects];

我知道这会导致崩溃,但这只是为了检查。在这里,如何检查数组是否有效?这是一个正确的方法还是别的什么?

请指导我。
谢谢。

实际代码:

- (void)getFriendsList{

    BOOL netIsAvailable = [self connected];

    if (netIsAvailable) {
        @try {
            NSString *accessToken = [self getAccessToken];
            NSString *tokenEncoded = [accessToken stringByReplacingOccurrencesOfString:@"\"" withString:@""];
            NSString *finalUrl = [NSString stringWithFormat:@"%@FriendsnSongs/%@",CommonWebServiceUrl,tokenEncoded];
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:finalUrl] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
            NSURLResponse *response = nil;
            NSError *error = nil;
            NSData *currentResult = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//            NSString* responseString = [[NSString alloc] initWithData:currentResult encoding:NSUTF8StringEncoding];

            if (currentResult != nil) {
                NSDictionary* json = [NSJSONSerialization
                                      JSONObjectWithData:currentResult
                                      options:kNilOptions
                                      error:&error];
                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                int statusCode = [httpResponse statusCode];

                NSMutableArray *match = [json valueForKey:@"FriendsnSongsResult"];
                if (statusCode == 200) {
                    if (self.userGuidArray) {
                        [self.albumNameArray removeAllObjects];  //here got crash
                        [self.artistNameArray removeAllObjects];
                        [self.deviceNameArray removeAllObjects]; //here also got crash once
                        [self.nickNameArray removeAllObjects];
                        [self.userProfileImageArray removeAllObjects];
                        [self.songTitleArray removeAllObjects];
                        [self.songStatusArray removeAllObjects];
                        [self.userGuidArray removeAllObjects];
                    }

                    for(NSArray *player in match) {
                        [self.albumNameArray addObject:[(NSArray *)player valueForKey:@"AlbumName"]];
                        [self.artistNameArray addObject:[(NSArray *)player valueForKey:@"Artist"]];
                        [self.nickNameArray addObject:[(NSArray *)player valueForKey:@"NickName"]];
                        [self.userProfileImageArray addObject:[(NSArray *)player valueForKey:@"ProfileImage"]];
                        [self.songStatusArray addObject:[(NSArray *)player valueForKey:@"Status"]];
                        [self.songTitleArray addObject:[(NSArray *)player valueForKey:@"Title"]];
                        [self.userGuidArray addObject:[(NSArray *)player valueForKey:@"UserGuid"]];
                        [self.deviceNameArray addObject:[(NSArray *)player valueForKey:@"DeviceName"]];
                    }
                    //Start timer for updating the friends list
                    if (timerActivated)
                        [self performSelectorOnMainThread:@selector(backgroundFriendsListUpdate) withObject:nil waitUntilDone:NO];
                    //Update table if the table not in search mode
                    if (!isSearching)
                        [self performSelectorOnMainThread:@selector(updateTable) withObject:nil waitUntilDone:YES];
                }
            }
        }
        @catch (NSException *exception) {
            NSLog(@"Exception: %@",exception.name);
        }
    }
    [DejalActivityView removeView];
}

重要的一点是,在这个类中,每 30 秒运行一个后台线程。它将调用相同的方法来刷新表。

4

2 回答 2

4

如果您正在使用,请从您的代码中ARC删除这一行,因为要处理它。否则写入方法。[testArray release];ARC[testArray release];-(void)dealloc

在删除数组值之前给出条件

if(myArray.count > 0)// because sometime it is good logic for us.
  [myArray removeAllObjects];

然后将数据插入myArray.

于 2013-03-19T09:33:56.463 回答
1

正如您在评论中建议的那样,使用临时数组是个好主意。以下代码将填充一个临时数组并使用它来替换主线程中的数组。

NSMutableArray *tempAlbumArray = [NSMutableArray array];
//fill your array
[tempAlbumArray addObject:<#some object#>];
dispatch_async(dispatch_get_main_queue(), ^{
    //replace your array with the new one
    //this code will be executed in main thread
    self.albumNameArray = tempAlbumArray;
});
于 2013-03-19T11:09:24.333 回答