2013-10-27 55 views
0

在我尝试索引用户名的数组中,我无法重新分配数据。我能够将我的原始数组分离为单个对象,但无法将该值发送给我需要稍后参考的新数组。我的self.userNamesArray = userNames;行中的userNames的值和计数是正确的。但之后,当我登录self.userNamesArray,我得到(null)。任何提示,因为我不完全确定我是干杯!访问可变数组时遇到问题

.H

@property (nonatomic, copy) NSMutableArray *userNamesArray;

.M

- (void)viewWillAppear:(BOOL)animated { 

self.friendsRelation = [[PFUser currentUser] objectForKey:@"friendsRelation"]; 

PFQuery *query = [self.friendsRelation query]; 
[query orderByAscending:@"username"]; 
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 
    if (error) { 
     NSLog(@"Error: %@ %@", error, [error userInfo]); 
    } 
    else { 
     self.friends = objects; 

     NSArray *users = [self.friends valueForKey:@"username"]; 
     NSLog(@"username:%@", users); 
     //Create an array of name wrappers and pass to the root view controller. 
     NSMutableArray *userNames = [[NSMutableArray alloc] initWithCapacity:[self.friends count]]; 

     for (NSString *user in users) { 

     componentsSeparatedByCharactersInSet:charSet]; 
      NSArray *nameComponents = [user componentsSeparatedByString:@" "]; 

      UserNameWrapper *userNameWrapper = [[UserNameWrapper alloc] initWithUserName:nil nameComponents:nameComponents]; 

      [userNames addObject:userNameWrapper]; 
     } 

     self.userNamesArray = userNames; 

     NSLog(@"userNamesArray:%@",self.userNamesArray); 

     [self.tableView reloadData]; 
    } 

这里就是我需要引用self.userNamesArray在那里再次,它是作曲了零代码。

- (void)setUserNamesArray:(NSMutableArray *)newDataArray { 

if (newDataArray != self.userNamesArray) { 
    self.userNamesArray = [newDataArray mutableCopy]; 
    if (self.userNamesArray == nil) { 
     self.sectionsArray = nil; 
     NSLog(@"user names empty"); 
    } 
    else { 
     [self configureSections]; 
    } 
} 

}

+0

请添加语言标签。 –

回答

1

将您可变阵列的属性方法更改为以下: -

@property (nonatomic, retain) 
    NSMutableArray *userNamesArray; 
+0

谢谢,我也试过,但结果仍然相同。 –

+0

在viewwillappear中更改此行并检查[self setUserNamesArray:[NSArray arrayWithObject:userNames]]; –

+0

试过了,我现在得到这个错误抛出:' - [__ NSArrayM userName]:无法识别的选择发送到实例0x1568fb50'我一直试图解决这一整天。也许我太累了。 –

0

首先,我没有你需要的NSMutableArray为 “userNamesArray”。你可以简单地使用NSArray。现在,请尝试下面的一段代码,你应该很好去:

self.userNamesArray = [NSMutableArray arrayWithArray:userNames]; 
1

这段代码是以递归方式调用自己吗?

self.userNamesArray = [newDataArray mutableCopy]; 

被equivilent到:

[self setUserNamesArray: [newDataArray mutableCopy]]; 

如果你需要重写分配期间发生了什么,你可以做你在这里做什么,但使用_userNamesArray引用底层成员的领域。

+0

我曾尝试使用_userNamesArray引用,但系统为此行抛出一个Bad Access错误'self.userNamesArray = [newDataArray mutableCopy];' –

0

你可能会得到null,因为这行:

NSArray *users = [self.friends valueForKey:@"username"];

将其更改为:

NSArray *users = [self.friends objectForKey:@"username"];

此外,遵循@Abhinav建议能有更多更清晰的代码:)