How to manage int when it's incremented inside another loop? - objective-c

I have a simple loop with an int counter that gets incremented inside a while loop when a special case exists. My question is simply - how should I manage memory inside this function with regards to the int specifically? I've been using NSNumber almost exclusively and what little time I've spent with int seems to make me think I'm not doing releasing it correctly.
Any other improvements are also welcome but I'm very interested in the int question
- (NSArray *)parseJson:(NSArray *) items
{
NSMutableArray* hats = [[NSMutableArray alloc] init];
NSEnumerator *enumerator = [items objectEnumerator];
NSDictionary* item;
int counterz = 0;
while (item = (NSDictionary*)[enumerator nextObject]) {
Hat* hat = [[Hat alloc] init];
hat.addr = [item objectForKey:#"Address"];
BOOL* hasHat = [item objectForKey:#"HasHat"];
if ([hasHat boolValue]) {
if (counterz < 10) {
[hats addObject:hat];
counterz++;
}
}
}
return hats;
}
Thank you in advance!

You don't need to release a "normal" (i.e.: non-object based) int - it'll happily life out its (brief, tragic) life on the stack until it falls out of scope.

You've got a couple unnecessary things and some memory leaks...
- (NSArray *)parseJson:(NSArray *) items {
NSMutableArray *hats = [NSMutableArray array];
int counter = 0;
for (NSDictionary *item in items) {
Hat *hat = [[Hat alloc] init];
[hat setAddr:[item objectForKey:#"Address"]];
BOOL hasHat = [[item objectForKey:#"HasHat"] boolValue];
if (hasHat && counter < 10) {
[hats addObject:hat];
counter++;
}
[hat release];
}
return hats;
}
And heck, once you reach a counter of 10, you could break out of the loop, because you're never going to do anything useful once 10 is reached.
Some other comments:
The name of the method is wrong. Nothing about this method has to do with parsing JSON. At best you're interpreting an array of dictionaries that happened to originate from a JSON string, but there's nothing about the nature of this code that says "this is parsing JSON".
-[NSDictionary objectForKey:] returns an object. A BOOL is not an object, it's a primitive (like an int or char). Appending * to the type does not make it an object either. :)
Since the method name does not begin with new or alloc and does not contain the word copy, you're supposed to return an autoreleased object from it. The method in the question was returning an owned object (+1 retain count), since you invoked alloc, but never autorelease. Using the convenience constructor +array fixes this.
In your loop, you allocated a Hat object, but never released it. This is a classic memory leak.

Related

declaring double arrays in objective-c

My map object has a set of coordinates. It doesn't always have the same number of coordinates.
In java I'd just declare the object as Double[] xpoints and would set it's size when instantiating a map like this: xpoints = new double[npoints];
How can I do this with objective-c?
I tried doing this: #property(nonatomic) double * xpoints; but somehow all of it's values turn to 0 when I print it with NSLog.
Map's init:
-(id)initWithXpoints:(double[]) xpointss Ypoints:(double[]) ypointss Npoints:(int)npointss
{
self = [super init];
if (self)
{
self.xpoints = xpointss;
self.ypoints = ypointss;
self.npoints = npointss;
}
return self;
}
Something weird happens though. The values are changed to zero when I print xpoints[0] from the object that created the map. The first time I print it it works. The second time it just prints zero.
I think it happens because xpointss sent to init is removed from the memory. How can I "instantiate" the xpoints property if it's a pointer?
Is there a better way to do this?
added: I tried creating a temporary xpoints like this:
double tempxpoints[npointss];
double tempypoints[npointss];
for (int i = 0; i < npointss; i++)
{
tempxpoints[i] = xpointss[i];
tempypoints[i] = ypointss[i];
}
self.xpoints = tempxpoints;
self.ypoints = tempypoints;
But it still didn't work.
Edit: Thanks for all the answers. This ended up being my final Init code:
-(id)initWithXpoints:(double[]) xpointss Ypoints:(double[]) ypointss Npoints:(int)npointss
{
self = [super init];
if (self)
{
_xpoints = [[NSMutableArray alloc] init];
_ypoints = [[NSMutableArray alloc] init];
for (int i = 0; i < npointss; i++)
{
NSNumber *tempx = [NSNumber numberWithDouble:xpointss[i]];
NSNumber *tempy = [NSNumber numberWithDouble:ypointss[i]];
[_xpoints addObject:tempx];
[_ypoints addObject:tempy];
}
_npoints = npointss;
}
return self;
}
If you allocate the arrays as local variables, then they will be allocated on the stack. When execution leaves the function, those memory areas are freed up. You must use malloc() to allocate arrays that you can pass around and use free() to free them up.
// to allocate
double[] tempxpoints = (double[])malloc(sizeof(double) * npointss);
// to free when not used any more
free(tempxpoints);
But actually NSArray has been designed to handle these cases. And with ARC you don't even have to care about freeing the memory.
NSMutableArray *tempxpoints = [[NSMutableArray alloc] init];
[tempxpoints addObject:#2]; // wrap the double in an NSNumber object
If you were being fully Objective-C about it, you'd use an NSArray, fill it with NSNumbers and never specify a length. You can usually give them hints about how much space is likely to be required but Objective-C's collections all always size dynamically.
As of recent versions of the compiler, you can use array[x] notation on NSArray and write direct NSNumber constants as e.g. #4.5f if that sweetens the deal at all.
If you literally want C-style arrays then you'll need to descend to the C level of thought. So, something like:
#property(nonatomic, readonly) double * xpoints;
And:
-(id)initWithXpoints:(double[]) xpointss Ypoints:(double[]) ypointss Npoints:(int)npointss
{
self = [super init];
if (self){
size_t sizeOfArraysInBytes = sizeof(double)*npointss;
_xpoints = (double *)malloc(sizeOfArraysInBytes);
memcpy(_xpoints, xpointss, sizeOfArraysInBytes);
/* ... etc ... */
/* you never use self. notation in an init because it's a method call,
and method calls on objects that are not yet fully instantiated aren't
safe. Sample cause of failure: a subclass overrides the setter */
}
return self;
}
- (void)dealloc
{
free(_xpoints);
/* ... etc ... */
}
The array itself will be read/write elsewhere (it's the pointer that's read-only, not the things it points to) as class.xpoints[0], etc.

Declaring a pointer in a loop

everyone. My "engrish" is not very good but I hope you will understand my problem.
Let's say I have a code like this
-(id) init
{
if ( self = [super init] )
{
deck = [[NSMutableArray alloc] initWithCapacity:52];
Card *newCard = [[Card alloc] init];
for ( int suit = 0; suit < 4; suit++ )
for ( int rank = 0; rank < 13; rank++ )
{
newCard.suit = suit;
newCard.rank = rank;
[deck addObject:newCard];
}
[newCard release];
}
return self;
}
I'm feeling like I have a mistake in the aforementioned code. I want to create 52 different objects in nested loops and add every object in array. But I suspect that I'll have 52 same objects and in array will be 52 pointers that point to the same address, right?
What happens if I make like this.
-(id) init
{
if ( self = [super init] )
{
deck = [[NSMutableArray alloc] initWithCapacity:52];
for ( int suit = 0; suit < 4; suit++ )
for ( int rank = 0; rank < 13; rank++ )
{
Card *newCard = [[Card alloc] init]; // I guess every time newCard
newCard.suit = suit; // created, it will point to
newCard.rank = rank; // another chunk of memory,
[deck addObject:newCard]; // right?
[newCard release] // Should I release newCard every time?
}
}
return self;
}
So which way I can create 52 different cards?
Thank you. If you need more explanations, ask me.
First question: Your second code sniplet produces 52 individual objects which you add to the array.
The first sniplet, as you already suggested yourself, produces just one object which you add to the array. As it is one object only all the members of the array will carry the same values for .suit and .rank.
Als suggested already, when you nslog the objects then you see at least their address in memory. When the address is identical then it is the identical object.
Second question:
Yes, you should release it unless you use ARC. addObject will automatically retain each added object and release it upon removal from the array. So be careful when you fetch the object from the array later and intend to use it further. Then you may have to retain it again.
Alternative to your -correct- code you can autorelease the object using:
Card *newCard = [[[Card alloc] init] autorelease]; // I guess every time newCard
newCard.suit = suit; // created, it will point to
newCard.rank = rank; // another chunk of memory,
[deck addObject:newCard]; // right?
//[newCard release]; // not required, autoreleased
(However, a semicolon is missing following the release statement. )

Differences between [NSArray arrayWithArray:] and [NSArray copy]

lately I work much with arrays and I'm wonder.. what's diffrences between those two lines.
NSArray *array = [NSArray arrayWithArray:someArray];
and
NSArray *array = [someArray copy];
Which of it is faster? What in case we have NSMutableArray and mutableCopy?
Which of it is faster?
Don't worry about it. Premature optimization.
The main difference: the first approach results in an autoreleased "copy" that you don't own and don't have to release, while you do own the object created on the second line.
Both arrays will be immutable, by the way.
In addition to the other answers, also note, that when someArray is nil,
the first line will make array point to an empty array and the second will make
it point to nil. This might be an important difference, especially in mutable arrays.
The difference between the two is that the latter will be retained. The former will be autoreleased.
Both versions make a shallow copy of the array.
NSMutableArray *notMutableReally = [NSArray arrayWithArray:aMutableArray];
Should give you a compiler warning as you will be trying to assign a NSArray to a NSMutableArray.
Use.
NSMutableArray *mutableArrayCopy = [NSMutableArray arrayWithArray:aMutableArray];
Which is faster? Dont worry, they are all far faster than the rest of the stuff you will be doing. Check with Instruments if you really care.
The main difference is that -copy knows better how to copy itself (can do it more efficiently and maybe use a more adapted subclass of NSArray) while +arrayWithArray: will create a new instance of NSArray (well, in fact the concrete class used by Foundation for arrays) and feed it with the same list of objects from the initial object. Also it will add an extra autorelease.
So -copy is (very very) likely more efficient.
In fact for immutable NSArrays, -copy is just doing -retain, so it does not even bother creating a new instance.
NSMutableArray *arr = [NSMutableArray array];
for ( int i = 0; i < 10000; i ++)
{
[arr addObject:#(i*1000000ULL)];
}
// MARK
// arr = (id)[NSArray arrayWithArray:arr];
NSTimeInterval t = [NSDate timeIntervalSinceReferenceDate];
NSArray *res = nil;
for ( int i = 0; i < 10000; i ++)
{
res = [arr copy];
}
NSLog(#"time A: %f", [NSDate timeIntervalSinceReferenceDate] - t);
t = [NSDate timeIntervalSinceReferenceDate];
for ( int i = 0; i < 10000; i ++)
{
res = [NSArray arrayWithArray:arr];
}
NSLog(#"time B: %f", [NSDate timeIntervalSinceReferenceDate] - t);
time A: 1.572795, time B: 1.539150, B [NSArray arrayWithArray:] always faster but time difference very small. But if we uncomment "MARK" and get copy from NSArray instead NSMutableArray we will have other runtime A: 0.000473 time B: 1.548400 result: ~3200x times faster
One of them is probably faster. Run them a million times and see if anyone wins.
In case of NSArray vs NSMutableArray, an immutable array being copied does not have to actually return a copy since it can't change. However, if you have a mutable array, it would need to be copied since you could change the original. And of course doing a mutable copy always needs to return a new object.
In your entire app, the speed and memory difference is probably not going to matter compared to everything else that's going on.
In Swift, it's very different. Thanks to the new open-source Foundation for Swift, we know that whereas init(array:) creates a new array with the items given (if any), copy() simply returns self.
public override func copy() -> AnyObject {
return copyWithZone(nil)
}
public func copyWithZone(zone: NSZone) -> AnyObject {
return self
}
https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSArray.swift#L82
public convenience init(array: [AnyObject]) {
self.init(array: array, copyItems: false)
}
public convenience init(array: [AnyObject], copyItems: Bool) {
let optionalArray : [AnyObject?] =
copyItems ?
array.map { return Optional<AnyObject>(($0 as! NSObject).copy()) } :
array.map { return Optional<AnyObject>($0) }
// This would have been nice, but "initializer delegation cannot be nested in another expression"
// optionalArray.withUnsafeBufferPointer { ptr in
// self.init(objects: ptr.baseAddress, count: array.count)
// }
let cnt = array.count
let buffer = UnsafeMutablePointer<AnyObject?>.alloc(cnt)
buffer.initializeFrom(optionalArray)
self.init(objects: buffer, count: cnt)
buffer.destroy(cnt)
buffer.dealloc(cnt)
}
https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSArray.swift#L116
So, obviously, copy() is faster, and now you know how they both work! (Just only in Swift)

Storing objects in an array in objective c

I'm trying to store 25 objects in an array
for (int iy=0; iy<5; iy++) {
for (int ix=0; ix<5; ix++) {
TerrainHex *myObject = [[TerrainHex alloc] initWithName:(#"grassHex instance 10000") width:mGameWidth height:mGameHeight indexX:ix indexY:iy];
myObject.myImage.y += 100;
[TerrainHexArray addObject:myObject];
[self addChild:(id)myObject.myImage];
}
}
NSLog(#"Terrain array: %u", [TerrainHexArray count]);
The log is coming back as zero though.
In the .h file I have
#property NSMutableArray *TerrainHexArray;
And in the .m file I have..
#synthesize TerrainHexArray;
I just tried what someone suggested below, which is..
NSMutableArray *TerrainHexArray = [[NSMutableArray] alloc] init];
But it's just giving me a warning saying expected identifier.
It's almost certain that TerrainHexArray does not exist when you're doing the addObject calls and the NSLog. You say you tried adding the alloc/init after someone suggested it, which indicates you don't understand object management in Objective-C.
I'd suggest you step back, find a book on Objective-C, and read at least the first few chapters (up through the discussion of alloc/init et al) before you attempt any more coding.
Incidentally, it's standard C++/Objective-C coding practice (except in Microsoft) to use identifiers with a leading lower case character for instance names, reserving leading caps for types/class names.
What is TerrainHexArray? It looks like a class name, not an instance of an array. If you create a mutable array, then you can add the items to the array.
NSMutableArray *hexArray = [[NSMutableArray] alloc] init];
for (int iy=0; iy<5; iy++) {
for (int ix=0; ix<5; ix++) {
TerrainHex *myObject = [[TerrainHex alloc] initWithName:(#"grassHex instance 10000") width:mGameWidth height:mGameHeight indexX:ix indexY:iy];
myObject.myImage.y += 100;
[hexArray addObject:myObject];
[self addChild:(id)myObject.myImage];
}
}
NSLog(#"Terrain array: %u", [hexArray count]);

Best way to remove from NSMutableArray while iterating?

In Cocoa, if I want to loop through an NSMutableArray and remove multiple objects that fit a certain criteria, what's the best way to do this without restarting the loop each time I remove an object?
Thanks,
Edit: Just to clarify - I was looking for the best way, e.g. something more elegant than manually updating the index I'm at. For example in C++ I can do;
iterator it = someList.begin();
while (it != someList.end())
{
if (shouldRemove(it))
it = someList.erase(it);
}
For clarity I like to make an initial loop where I collect the items to delete. Then I delete them. Here's a sample using Objective-C 2.0 syntax:
NSMutableArray *discardedItems = [NSMutableArray array];
for (SomeObjectClass *item in originalArrayOfItems) {
if ([item shouldBeDiscarded])
[discardedItems addObject:item];
}
[originalArrayOfItems removeObjectsInArray:discardedItems];
Then there is no question about whether indices are being updated correctly, or other little bookkeeping details.
Edited to add:
It's been noted in other answers that the inverse formulation should be faster. i.e. If you iterate through the array and compose a new array of objects to keep, instead of objects to discard. That may be true (although what about the memory and processing cost of allocating a new array, and discarding the old one?) but even if it's faster it may not be as big a deal as it would be for a naive implementation, because NSArrays do not behave like "normal" arrays. They talk the talk but they walk a different walk. See a good analysis here:
The inverse formulation may be faster, but I've never needed to care whether it is, because the above formulation has always been fast enough for my needs.
For me the take-home message is to use whatever formulation is clearest to you. Optimize only if necessary. I personally find the above formulation clearest, which is why I use it. But if the inverse formulation is clearer to you, go for it.
One more variation. So you get readability and good performace:
NSMutableIndexSet *discardedItems = [NSMutableIndexSet indexSet];
SomeObjectClass *item;
NSUInteger index = 0;
for (item in originalArrayOfItems) {
if ([item shouldBeDiscarded])
[discardedItems addIndex:index];
index++;
}
[originalArrayOfItems removeObjectsAtIndexes:discardedItems];
This is a very simple problem. You just iterate backwards:
for (NSInteger i = array.count - 1; i >= 0; i--) {
ElementType* element = array[i];
if ([element shouldBeRemoved]) {
[array removeObjectAtIndex:i];
}
}
This is a very common pattern.
Some of the other answers would have poor performance on very large arrays, because methods like removeObject: and removeObjectsInArray: involve doing a linear search of the receiver, which is a waste because you already know where the object is. Also, any call to removeObjectAtIndex: will have to copy values from the index to the end of the array up by one slot at a time.
More efficient would be the following:
NSMutableArray *array = ...
NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];
for (id object in array) {
if (! shouldRemove(object)) {
[itemsToKeep addObject:object];
}
}
[array setArray:itemsToKeep];
Because we set the capacity of itemsToKeep, we don't waste any time copying values during a resize. We don't modify the array in place, so we are free to use Fast Enumeration. Using setArray: to replace the contents of array with itemsToKeep will be efficient. Depending on your code, you could even replace the last line with:
[array release];
array = [itemsToKeep retain];
So there isn't even a need to copy values, only swap a pointer.
You can use NSpredicate to remove items from your mutable array. This requires no for loops.
For example if you have an NSMutableArray of names, you can create a predicate like this one:
NSPredicate *caseInsensitiveBNames =
[NSPredicate predicateWithFormat:#"SELF beginswith[c] 'b'"];
The following line will leave you with an array that contains only names starting with b.
[namesArray filterUsingPredicate:caseInsensitiveBNames];
If you have trouble creating the predicates you need, use this apple developer link.
I did a performance test using 4 different methods. Each test iterated through all elements in a 100,000 element array, and removed every 5th item. The results did not vary much with/ without optimization. These were done on an iPad 4:
(1) removeObjectAtIndex: -- 271 ms
(2) removeObjectsAtIndexes: -- 1010 ms (because building the index set takes ~700 ms; otherwise this is basically the same as calling removeObjectAtIndex: for each item)
(3) removeObjects: -- 326 ms
(4) make a new array with objects passing the test -- 17 ms
So, creating a new array is by far the fastest. The other methods are all comparable, except that using removeObjectsAtIndexes: will be worse with more items to remove, because of the time needed to build the index set.
Either use loop counting down over indices:
for (NSInteger i = array.count - 1; i >= 0; --i) {
or make a copy with the objects you want to keep.
In particular, do not use a for (id object in array) loop or NSEnumerator.
For iOS 4+ or OS X 10.6+, Apple added passingTest series of APIs in NSMutableArray, like – indexesOfObjectsPassingTest:. A solution with such API would be:
NSIndexSet *indexesToBeRemoved = [someList indexesOfObjectsPassingTest:
^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [self shouldRemove:obj];
}];
[someList removeObjectsAtIndexes:indexesToBeRemoved];
Nowadays you can use reversed block-based enumeration. A simple example code:
NSMutableArray *array = [#[#{#"name": #"a", #"shouldDelete": #(YES)},
#{#"name": #"b", #"shouldDelete": #(NO)},
#{#"name": #"c", #"shouldDelete": #(YES)},
#{#"name": #"d", #"shouldDelete": #(NO)}] mutableCopy];
[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if([obj[#"shouldDelete"] boolValue])
[array removeObjectAtIndex:idx];
}];
Result:
(
{
name = b;
shouldDelete = 0;
},
{
name = d;
shouldDelete = 0;
}
)
another option with just one line of code:
[array filterUsingPredicate:[NSPredicate predicateWithFormat:#"shouldDelete == NO"]];
In a more declarative way, depending on the criteria matching the items to remove you could use:
[theArray filterUsingPredicate:aPredicate]
#Nathan should be very efficient
Here's the easy and clean way. I like to duplicate my array right in the fast enumeration call:
for (LineItem *item in [NSArray arrayWithArray:self.lineItems])
{
if ([item.toBeRemoved boolValue] == YES)
{
[self.lineItems removeObject:item];
}
}
This way you enumerate through a copy of the array being deleted from, both holding the same objects. An NSArray holds object pointers only so this is totally fine memory/performance wise.
Add the objects you want to remove to a second array and, after the loop, use -removeObjectsInArray:.
this should do it:
NSMutableArray* myArray = ....;
int i;
for(i=0; i<[myArray count]; i++) {
id element = [myArray objectAtIndex:i];
if(element == ...) {
[myArray removeObjectAtIndex:i];
i--;
}
}
hope this helps...
Why don't you add the objects to be removed to another NSMutableArray. When you are finished iterating, you can remove the objects that you have collected.
How about swapping the elements you want to delete with the 'n'th element, 'n-1'th element and so on?
When you're done you resize the array to 'previous size - number of swaps'
If all objects in your array are unique or you want to remove all occurrences of an object when found, you could fast enumerate on an array copy and use [NSMutableArray removeObject:] to remove the object from the original.
NSMutableArray *myArray;
NSArray *myArrayCopy = [NSArray arrayWithArray:myArray];
for (NSObject *anObject in myArrayCopy) {
if (shouldRemove(anObject)) {
[myArray removeObject:anObject];
}
}
benzado's anwser above is what you should do for preformace. In one of my applications removeObjectsInArray took a running time of 1 minute, just adding to a new array took .023 seconds.
I define a category that lets me filter using a block, like this:
#implementation NSMutableArray (Filtering)
- (void)filterUsingTest:(BOOL (^)(id obj, NSUInteger idx))predicate {
NSMutableIndexSet *indexesFailingTest = [[NSMutableIndexSet alloc] init];
NSUInteger index = 0;
for (id object in self) {
if (!predicate(object, index)) {
[indexesFailingTest addIndex:index];
}
++index;
}
[self removeObjectsAtIndexes:indexesFailingTest];
[indexesFailingTest release];
}
#end
which can then be used like this:
[myMutableArray filterUsingTest:^BOOL(id obj, NSUInteger idx) {
return [self doIWantToKeepThisObject:obj atIndex:idx];
}];
A nicer implementation could be to use the category method below on NSMutableArray.
#implementation NSMutableArray(BMCommons)
- (void)removeObjectsWithPredicate:(BOOL (^)(id obj))predicate {
if (predicate != nil) {
NSMutableArray *newArray = [[NSMutableArray alloc] initWithCapacity:self.count];
for (id obj in self) {
BOOL shouldRemove = predicate(obj);
if (!shouldRemove) {
[newArray addObject:obj];
}
}
[self setArray:newArray];
}
}
#end
The predicate block can be implemented to do processing on each object in the array. If the predicate returns true the object is removed.
An example for a date array to remove all dates that lie in the past:
NSMutableArray *dates = ...;
[dates removeObjectsWithPredicate:^BOOL(id obj) {
NSDate *date = (NSDate *)obj;
return [date timeIntervalSinceNow] < 0;
}];
Iterating backwards-ly was my favourite for years , but for a long time I never encountered the case where the 'deepest' ( highest count) object was removed first. Momentarily before the pointer moves on to the next index there ain't anything and it crashes.
Benzado's way is the closest to what i do now but I never realised there would be the stack reshuffle after every remove.
under Xcode 6 this works
NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];
for (id object in array)
{
if ( [object isNotEqualTo:#"whatever"]) {
[itemsToKeep addObject:object ];
}
}
array = nil;
array = [[NSMutableArray alloc]initWithArray:itemsToKeep];