所以我正在创建一个联系人列表应用程序,并将所有内容存储到一个 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/