ios 来自 NSArray 的 NSMutableArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4372825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:14:34  来源:igfitidea点击:

NSMutableArray from NSArray

iosobjective-cnsmutablearraynsarray

提问by Tom Kelly

i have the following code and i want to use NSMutable arrays instead of NSArray could you tell me how to load the NSMutable array, as the current method does not work.

我有以下代码,我想使用 NSMutable 数组而不是 NSArray 你能告诉我如何加载 NSMutable 数组,因为当前方法不起作用。

-(void) whatever{
NSData *htmlData = [[NSString stringWithContentsOfURL:[NSURL URLWithString: @"http://www.objectgraph.com/contact.html"]] dataUsingEncoding:NSUTF8StringEncoding];
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
NSArray *titles  = [xpathParser search:@"//h3"]; // get the page title - this is xpath     notation
TFHppleElement *title = [titles objectAtIndex:0];
NSString *myTitles = [title content];

NSArray *articles  = [xpathParser search:@"//h4"]; // get the page article - this is xpath     notation
TFHppleElement *article = [articles objectAtIndex:0];
NSString *myArtical = [article content];

i have tried :

我试过了 :

NSMutableArray *titles  = [xpathParser search:@"//h3"];

but it does load the values?

但它确实加载了值?

回答by Jacob Relkin

You can invoke mutableCopyon an NSArrayobject to return to you an NSMutableArray.

你可以调用mutableCopy一个NSArray对象来返回给你一个NSMutableArray.

Note that the callee will obtain ownership of this object since the method name contains "copy".

请注意,被调用者将获得此对象的所有权,因为方法名称包含“copy”。

(Apple's memory management guidestates that a method name containing the words "alloc", "new" or "copy" should by convention return an object which you own, and as such must relinquish ownership of at some point.)

Apple 的内存管理指南指出,按照约定,包含“alloc”、“new”或“copy”字样的方法名称应返回您拥有的对象,因此必须在某个时候放弃所有权。)

回答by jer

Simply like this:

就像这样:

NSArray* someArray = [xpathParser search:@"//h3"];
NSMutableArray* mutableArray = [someArray mutableCopy];

That's quite literally, it.

顾名思义,就是这样。

回答by Rog

Assuming [xpathparser ...]returns an NSArray, you can use:

假设[xpathparser ...]返回一个NSArray,您可以使用:

NSMutableArray *titles  = [NSMutableArray arrayWithArray:[xpathParser search:@"//h3"]];