如何将 NSArray 转换为 NSMutableArray [英] How to convert NSArray to NSMutableArray
问题描述
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
NSMutableArray *tempPeoples=[[NSMutableArray alloc]init];
for(int i=0;i<nPeople;i++){
ABRecordRef i1=CFArrayGetValueAtIndex(allPeople, i);
[tempPeoples addObject:i1];
// [peoples addObject:i1];
}// end of the for loop
peoples=[tempPeoples copy];
这段代码给出了异常 b/c 我想将 NSMutableArray 转换为 NSArray请帮忙
This code gives exception b/c I want to convert NSMutableArray to NSArray Please Help
推荐答案
主题内容为如何将 NSArray
转换为 NSMutableArray
".要从 NSArray
获取 NSMutableArray
,请使用 NSMutableArray
+arrayWithArray
上的类方法:.
The subject reads, "How to convert NSArray
to NSMutableArray
". To get an NSMutableArray
from an NSArray
, use the class method on NSMutableArray
+arrayWithArray
:.
您的代码没有显示人民的声明.假设它被声明为 NSMutableArray
,如果你试图这样对待它,你可能会遇到问题.当您将复制消息发送到 NSMutableArray
时,您将获得一个不可变对象 NSArray
,因此如果您尝试将一个对象添加到复制的 NSMutableArray
>,你会得到一个错误.
Your code does not show the declaration for peoples. Assuming it's declared as an NSMutableArray
, you can run into problems if you try to treat it as such. When you send the copy message to an NSMutableArray
, you get an immutable object, NSArray
, so if you try to add an object to a copied NSMutableArray
, you will get an error.
CFArrayRef
是免费桥接到 NSArray
的,所以你可以这样简化你的代码:
CFArrayRef
is toll free bridged to NSArray
, so you could simplify your code this way:
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
//NSMutableArray *tempPeoples = [NSMutableArray arrayWithArray:(NSArray*)allPeople];
// even better use the NSMutableCopying protocol on NSArray
NSMutableArray *tempPeoples = [(NSArray*)allPeople mutableCopy];
CFRelease(allPeople);
return tempPeoples; // or whatever is appropriate to your code
在上面的代码中 tempPeoples 是一个自动发布的 NSMutableArray
准备好根据需要添加或删除对象.
In the above code tempPeoples is an autoreleased NSMutableArray
ready for you to add or remove objects as needed.
这篇关于如何将 NSArray 转换为 NSMutableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!