【问题标题】:Is this the best way to set objective c arrays equal to oneanother?这是将目标 c 数组设置为彼此相等的最佳方法吗?
【发布时间】:2011-06-20 18:07:37
【问题描述】:

我这里有两个数组来自另一个类,一个是我在函数中创建的,我的最终目标是让 teamRoster 按字母顺序排序,这似乎可行,但有人可以告诉我是否有更好的方法吗?谢谢。

-(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];
}

【问题讨论】:

  • 您想在正确的排序位置插入您的新全名吗?而不是使用插入的新全名重新排序整个数组。如果您在谈论数组中的数百或数千个元素,这确实是优化的,您可以首先使用二进制搜索确定位置,然后在该位置插入。

标签: iphone objective-c ios xcode nsarray


【解决方案1】:

有没有更好的方法?取决于您所说的“更好”。

您的代码正确且易于理解。

假设teamRosterNSMutableArray 类型的属性,您可以简单地对其进行排序:

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

但可能有理由不这样做,比如性能或并发性。

另一方面,您可能希望保护 teamRoster 数组不被应用程序委托之外的代码修改,在这种情况下,您应该只将其作为不可变的 NSArray 提供,您将无法使用上面的排序。

【讨论】:

    【解决方案2】:

    这个怎么样?

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

    如果您的应用委托将 teamRoster 设置为属性,则设置器将允许您替换旧数组,而无需清空并重新填充它。

    【讨论】:

      【解决方案3】:

      试试这个:

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

      这是假设您有一个允许您更改 teamRoster 的属性设置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多