2012-10-12 34 views
0

我目前正在创建我的iPhone应用程序的一部分,基本上有一个单元格列表(在tableview中),这就像现有的苹果记事本一样。如何在iOS编程中获得每一枚枚举?

我想让它的单元格的名称有数组中的字符串的名称。这是我目前正在做的。

@interface ViewController() 
{ 
NSMutableArray *cameraArray; 
NSMutableArray *notesArray; 
NSMutableArray *voiceArray; 
} 
@end 

@implementation ViewController 
//@synthesize myTableView; 
- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

NSUserDefaults *ud=[NSUserDefaults standardUserDefaults]; 
//[ud setObject:@"Archer" forKey:@"char1class"]; 
[ud synchronize]; 
NSString *key1;//[ud stringForKey:@"Key1"]; 
NSString *key2; //[ud stringForKey:@"Key1"]; 
NSString *key3; //[ud stringForKey:@"Key1"]; 

if([ud stringForKey:@"Key1"] == nil){ 
    key1 = @"Open Camera Slot"; 
}else{ 
    key1 = [ud stringForKey:@"key1"]; 
} 

if([ud stringForKey:@"Key2"] == nil){ 
    key2 = @"Open Camera Slot"; 
}else{ 
    key2 = [ud stringForKey:@"key2"]; 
} 

if([ud stringForKey:@"Key3"] == nil){ 
    key3 = @"Open Camera Slot"; 
}else{ 
    key3 = [ud stringForKey:@"key3"]; 
} 

cameraArray = [[NSMutableArray alloc]initWithObjects:key1, key2, key3, nil]; 


} 

//tableview datasource delegate methods 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
    return 1; 
} 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    return cameraArray.count; 
} 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath{ 


CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; 


if(cell == nil){ 
    cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:@"Cell"]; 
} 

NSEnumerator *enumerator = [cameraArray objectEnumerator]; 
id anObject; 
NSString *cellName = nil; 
while (anObject = [enumerator nextObject]) { 
    cellName = anObject; 
} 
//static NSString *cellName = [cameraArray.objectAtIndex]; 
cell.textLabel.text = [NSString stringWithFormat:cellName]; 
return cell; 

} 

所以我基本上是从键在创建NSUserDefaults的在cameraArray字符串(我只是做这个测试的目的,字符串将用户输入以后)

我卡上的是什么枚举器遍历数组很好,但只使用tableView中所有单元格的最后一个值(第三个值)。

因此,如果有三根弦,“第一”“第二”和“第三”所有这三种细胞的说,“第三”

我该如何解决这个问题?

+0

您总是将当前枚举值分配给cellName,因此每次cellName值都被重置。另外,你想完成什么? – aqua

+2

你为什么要进行枚举?这是一个完全不必要的步骤:cell.textLabel.text = [cameraArray objectAtIndex:indexPath.row]; – rdelmar

+0

感谢rdelmar,解决了我的问题 – tyler53

回答

0

这段代码有几个错误。 'rdelmar'在他的评论中发布了基本答案。我以为我会做一些学习练习。

您在此处使用枚举器遍历数组的值。有一个更简单的方法。请注意,这不是您的代码所必需的。我正在指出这一点以备将来参考。

替换枚举,anObject,单元名称和while循环与此:

for (NSString *cellName in cameraArray) { 
    // Do something with cellName 
} 

这是通过NSString对象的数组中的所有值走更简单的方法。如果数组包含不同类型的对象,则用适当的类型替换NSString。

接下来是您使用创建一个新的字符串结合使用stringWithFormat :.在这种情况下也不需要。在你发布的代码中,cellName已经是一个NSString引用。直接分配,如:

cell.textLabel.text = cellName; 

不需要创建新的NSString对象。当你实际上有一个字符串格式时,你应该只使用字符串格式。

希望有所帮助。

+0

作为SO的新贡献者,有人可以解释为什么我的答案被拒绝投票吗?帮助新开发人员编写更好的代码不合适吗? – rmaddy

+0

感谢您帮助我,我实际上将它清理干净,以便在我检查您的答案之前完成您描述的内容:P我正在遵循一个不明确的教程来制作该代码,然后我自己回去清理它自己 – tyler53