简体   繁体   English

这是设置目标c数组彼此相等的最佳方法吗?

[英]Is this the best way to set objective c arrays equal to oneanother?

I have two arrays here on is from another class and one i have created in the function, my end goal is to have teamRoster sorted alphabetically, this seems to work but could someone please tell me if there is a better way? 我这里有两个数组是从另一个类中创建的,我是在函数中创建的,我的最终目标是让teamRoster按字母顺序排序,这似乎可行,但是有人可以告诉我是否有更好的方法吗? Thanks. 谢谢。

-(IBAction)submitAndSendBack:(id)sender{
        CoCoachAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

        NSString *fullName = [ NSString stringWithFormat:@"%@ %@",firstName.text, lastName.text];   
        [[appDelegate teamRoster] addObject:fullName];
        NSArray *temp = [[appDelegate teamRoster] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

        [[appDelegate teamRoster] removeAllObjects];
        [[appDelegate teamRoster] addObjectsFromArray:temp];


        NSLog(@"%@", [appDelegate teamRoster]);

        [ap

pDelegate.navigationController popViewControllerAnimated:YES];
}

Is there a better way? 有没有更好的办法? Depends on what you mean by "better". 取决于您所说的“更好”。

Your code is correct and easy enough to understand. 您的代码正确且容易理解。

Assuming teamRoster is a property of type NSMutableArray , you could simply sort it in place: 假设teamRosterNSMutableArray类型的属性,您可以简单地对其进行排序:

[[appDelegate teamRoster] sortUsingSelector:@selector(caseInsensitiveCompare:)];

But there might be reasons NOT to do it that way, say for performance or concurrency. 但是,出于性能或并发性的考虑,可能有理由不这样做。

On the other hand, you might want to protect the teamRoster array from being modified by code outside of the app delegate, in which case you should only make it available as an immutable NSArray, and you wouldn't be able to use the above to sort it. 另一方面,您可能想保护teamRoster数组不被应用程序委托外部的代码修改,在这种情况下,您只能将其作为不可变的NSArray使用,而您将无法使用以上代码来解决。

Try this: 尝试这个:

appDelegate.teamRoster = [[temp mutableCopy] autorelease];

That is assuming you have a property setup that allows you to change teamRoster. 假设您具有一个属性设置,可以更改teamRoster。

How about this? 这个怎么样?

NSArray *temp = [[appDelegate teamRoster] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
[appDelegate setTeamRoster:temp];

If your app delegate has a teamRoster set up as a property, the setter will let you replace the old array without having to empty it and refill it. 如果您的应用程序委托将teamRoster设置为属性,则设置器将允许您替换旧数组,而无需将其清空并重新填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM