我有自己的类定义如下。
@interface PersonList : NSObject
@property(nonatomic, strong)NSNumber *ID;
@property(nonatomic, strong)NSString *FirstName;
@property(nonatomic, strong)NSString *SecondName;
@end
我像以下方法一样使用它:
PersonList *P = [[PersonList alloc]init];
[P setID: ...];
[P setFirstname:...];
[P setSecondname:...];
然后将其添加到数组中。
[PersonListArray addObject:P];
我尝试做的是在此数组中搜索ID = x的类。
这是最好的方式吗?
for(int i = 0; i < PersonListArray.count; i++)
{
PersonListArray *aPersonListArray = [PersonListArray objectAtIndex:i];
if(aPersonListArray.ID == x)
{
//Do what i want here
//break;
}
}
由于
答案 0 :(得分:2)
您可以使用此NSArray
方法,使事情变得更轻松,也非常优化:
- (NSUInteger)indexOfObjectPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate
您的代码应该是这样的:
NSInteger personIndex = [PersonListArray indexOfObjectPassingTest:^BOOL(PersonList person, NSUInteger idx, BOOL *stop) {
return [person.ID isEqualToNumber:x];
}];
PersonList personList = PersonListArray[personIndex]
还有两件事:
equalTo
方法,而不是用于比较指针的==
符号希望这有帮助,
答案 1 :(得分:1)
还有另一种方式,更简单一点:
for(PersonList *AnyPerson in PersonListArray)
{
if([AnyPerson.ID isEqualToNumber:x])
{
//do what you want
}
}
答案 2 :(得分:1)
你可以这样做:
for(PersonList *person in PersonListArray){
if([person.ID isEqualToNumber: x]){
// do your job, it you want to do it for the first case only
// use break here or return depends on the case
}
}
看看比较值的方式(如果你想要比平等更多考虑使用compare:
方法)
顺便说一下,如果有可能性和性能,take a look at this可能有必要了解排序和搜索数组的可能性。
答案 3 :(得分:1)
试试这个
@interface PersonList ()
@property (nonatomic, strong) NSMutableArray *persons;
@end
@implementation PersonList
-(NSMutableArray *)persons{
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
_persons=[[NSMutableArray alloc] init];
});
return _persons;
}
-(instancetype)initWithIDs:(NSArray *)personIDs FirstNames:(NSArray *)firstNames SecondNames:(NSArray *)secondNames{
if(self=[super init]){
[personIDs enumerateObjectsUsingBlock:^(id personID, NSUInteger idx, BOOL *stop) {
NSMutableDictionary *person=[[NSMutableDictionary alloc] init];
[person setObject:personID forKey:@"ID"];
[person setObject:[firstNames objectAtIndex:idx] forKey:@"FIRSTNAME"];
[person setObject:[secondNames objectAtIndex:idx] forKey:@"SECONDNAME"];
[self.persons addObject:person];
}];
}
return self;
}
-(NSDictionary *)findPersonByID:(NSString *)personID{
__block NSDictionary *dictionary=[[NSDictionary alloc] init];
[self.persons enumerateObjectsUsingBlock:^(id person, NSUInteger idx, BOOL *stop) {
if ([[person objectForKey:@"ID"] isEqualToString:personID]) {
dictionary=person;
*stop=YES;
}
}];
return dictionary;
}
@end