ios - 通过数组排序 - Objective-C/iOS

标签 ios objective-c

所以我正在创建一个联系人列表应用程序,并将所有内容存储到一个 NSMutableArray 中。我已经设法使添加功能完美运行。但是我在使用 Previous/Next 功能时遇到了困难。

当按下上一个时,我可以让它返回数组中的一个对象,但我不能让它再返回?这是我的代码:我有两个额外的类,PhoneBookEntry,它是 Person 类的子类。这些类包含三个字符串,Firstname,lastname 和 studentID

- (IBAction)addPerson:(id)sender {
    PhonebookEntry *person = [[PhonebookEntry alloc] init];
    NSLog(@"%@",self.firstName.text);

    person.firstName = self.firstName.text;
    person.lastName = self.lastName.text;
    person.phoneNumber = self.phoneNumber.text;

    [self.entries addObject:person];

这是我的“上一个”按钮:

int length;
length = [self.entries count];

if (length > 0) {
    int index;
    index = [self.entries count] - 1;
    NSLog (@"%d the index is", index);

    NSLog(@"object %@", [self.entries objectAtIndex:index]);
} else {
    NSLog (@"No contacts have been entered. No");
}

//NSLog(@"%d is the length - 1 hopefully", length);
//NSLog (@"index at %d is ", length);

我试过在此处删除 - 1:

index = [self.entries count] - 1;

然后在下一行更改 index--;但似乎没有任何效果。它只返回一次。

我知道 length 是获取索引中的对象数量,然后是 -1 但我不应该在计数结束时/- 1 每次按下时继续删除它吗??

有什么想法吗?干杯

最佳答案

您将继续使用该段代码访问相同的索引 - 您需要将状态存储在某处。谁将持有当前指数?有了一个设计良好的系统,模型应该真正解决这个问题。

最好将当前索引存储到一个 ivar 中,并在每次按下按钮时更新它。

@interface OKAClass ()
  @property (nonatomic, assign) NSInteger currentIndex;
@end

//... initialise the property with a default value

self.currentIndex = [self.entries count] - 1;

//... when the button is pressed decrement the index (you might want some min / max validation or use modulus to loop over and start from the top again)

NSLog(@"%@", self.entries[self.currentIndex--]);

关于ios - 通过数组排序 - Objective-C/iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22419211/

相关文章:

ios - 在 Sprite Kit 中使用 Core Graphics

ios - 自动布局 - 使用约束优先级的一个 Storyboard 的纵向和横向?

ios - 画一个表盘状的线指向用户的触摸点

ios - 如何在对象 C 或 Swift 中获取设备序列号

objective-c - 我如何使用给定的nativeID(在react-native中给出)识别objective c中的 View

ios - NSPredicate & Parse 让它从数组中返回与当前用户匹配的结果,以及用户名字符串

ios - MapKit 注释消失

ios - SpriteKit世界定位错误

objective-c - CoreData 无法完成错误

objective-c - 如何查找 NSDate 是否在指定范围内?