NSMutableArray from NSArray
25,839
Solution 1
You can invoke mutableCopy
on an NSArray
object to return to you an NSMutableArray
.
Note that the callee will obtain ownership of this object since the method name contains "copy".
(Apple's memory management guide states 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.)
Solution 2
Simply like this:
NSArray* someArray = [xpathParser search:@"//h3"];
NSMutableArray* mutableArray = [someArray mutableCopy];
That's quite literally, it.
Solution 3
Assuming [xpathparser ...]
returns an NSArray
, you can use:
NSMutableArray *titles = [NSMutableArray arrayWithArray:[xpathParser search:@"//h3"]];
Author by
Tom Kelly
Updated on April 16, 2020Comments
-
Tom Kelly about 4 years
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.
-(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?
-
Nick Forge over 13 years
+[NSMutableArray arrayWithArray:]
has the benefit of being autoreleased - if you use-[NSArray mutableCopy]
, you'll need to release/autorelease yourself. -
JeremyP over 13 yearsI would up voted you but you wrote "should by convention return an object with a reference count = 1" which is technically wrong. In fact if you read your own link you'll see it doesn't even use the phrase "retain count" in the object ownership policy section.
-
JeremyP over 13 yearsYou've missed the point. Apple's memory management guide says the convention is that you own the object. It's an implementation detail that the retain count is 1 (which isn't always true anyway).
-
Basil Bourque over 11 yearsIs comment by Nick Forge now irrelevant under ARC?
-
James almost 11 years@BasilBourque no, some older but still maintained apps still use MRR
-
jer over 10 yearsI'd still recommend my way if you're using MRC, just make sure to do
[[someArray mutableCopy] autorelease]
instead if you want it autoreleased.