将字符串与NSArray进行比较

时间:2011-05-30 20:03:39

标签: iphone nsstring nsmutablearray compare

我必须对Checkin和FriendList进行分类。

Checkin.h

@interface Checkin : NSObject {

    NSString *name;
    NSString *profID;
    NSString *place;
    NSString *photoURL;
    NSMutableArray *taggedID;
    NSMutableArray *taggedName;

和Friendlist.h

@interface FriendList : NSObject {
    NSString *name;
    NSString *profID;

}

我要做的是将每个checkin.profid(大约5-6)与friendlist.h(200-5000)进行比较。 我尝试用for循环但是当检查第二个checkin.profid崩溃时。 这是我的方法:

  for(int i=0; i<[checkinArray count];i++){

     Checkin *tempcheck = [[Checkin alloc] init];
     tempcheck = [checkinArray objectAtIndex:i];

     for(int j=0;j<[friendsArray count]; j++){
         NSLog(@"count %d",j);
         FriendList *tempfriend = [[FriendList alloc] init];
         tempfriend  = [friendsArray objectAtIndex:j];

         if([tempcheck.profID isEqualToString:tempfriend.profID]){
             NSLog(@"Find prof id same for : %@",tempcheck.name);
             break;
         }
           else
             NSLog(@"Not found id same for: %@",tempcheck.name);
         [tempfriend release]; 
     }

    [tempcheck release];
   }
}

有没有更好的方法来进行这种比较?因为它也太慢了。 提前谢谢

2 个答案:

答案 0 :(得分:1)

这不会有所帮助:

Checkin *tempcheck = [[Checkin alloc] init];
     tempcheck = [checkinArray objectAtIndex:i];

FriendList *tempfriend = [[FriendList alloc] init];
tempfriend  = [friendsArray objectAtIndex:j];

没有理由分配它们:只需将它设置为所需索引的对象:

Checkin *tempcheck = [checkinArray objectAtIndex:i];

会更好。至于执行查找,为什么不循环检查并为每个checkin.profId实例化一个新的NSPredicate以通过friendlist查找profId。尝试[NSPredicate filterWithFormat:@“(profId =%@)”];

然后在你的数组上使用filteredArrayUsingPredicate。

答案 1 :(得分:1)

你的记忆管理全部破裂了。当你做这样的事情时:

 Checkin *tempcheck = [[Checkin alloc] init];
 tempcheck = [checkinArray objectAtIndex:i];

您正在做的是创建一个对象,然后将指针指定给签入数组中的对象。这会导致内存泄漏。

然后,稍后你做的时候:

[tempcheck release];

你是在对数组中的对象进行释放,而不是之前分配的对象。这可能导致数组中的对象被垃圾收集,然后当你第二次尝试访问它时会发生崩溃。

删除allocs&amp;发布并做这样的事情:

Checkin *tempcheck = [checkinArray objectAtIndex:i];