Objective-C multiple pointers to same object? [closed] - objective-c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Ive searched around and can't find any answers that aren't related to C++, which isn't the exact same thing. I have a game and I keep an NSMutableArray of my sprites for certain categories because there are too many of them and they appear/dissapear too often to keep references to every single one of them, and also the number of them varies. so they are stored in an array.
In my didBeginContact method I grab the contact.bodyA.node object and pass it into a mehtod I've written called getSprite which enumerates over the array of objects I have, finds the one that matches and returns that one as an SKSpriteNode so I can use SKSpriteNode-specific methods such as animateWithFrames and such. However, I use this method pretty frequently and I'm wondering if doing something like:
SKSpriteNode *sprite = (SKSpriteNode*)[contact.bodyB.node parent];
Is acceptable as well, and then just using that pointer to refer to my object. It works, but I don't know if it will cause memory leaks or other problems. Any suggestions? (the reason I used the parent method is because the sprite I'm actually after is the parent of the one involved in the collision).

I assume you're using ARC. The local pointer to the object is a strong pointer by default, since you didn't specify anything differently. So that object is guaranteed to not be destroyed during the scope in which your local sprite pointer exists. It will not maintain a strong reference beyond that scope. The NSMutableArray also maintains a strong reference to to the objects it contains, so while they are in that array, the objects will not be destroyed.

As far as memory leaks go, this shouldn't cause any problems. It should also be more performant since it's a direct link back up to the sprite, rather than iterating and searching for the correct sprite. I don't see any reason why you couldn't do that, besides the fact that is might affect future plans for your game since the parent relationship of the object becomes part of the logic when is probably shouldn't be, but if you centralize that code so it's easy to change if you ever change the hierarchy of your sprites it should be fine.

Related

Objective C's ARC vs C++'s Manual Memory Management [duplicate]

This question already has answers here:
What are the advantages and disadvantages of using ARC? [closed]
(4 answers)
Closed 9 years ago.
One possible exam question reads as follows:
"Explain the benefits and drawbacks of Objective C's memory management when compared to c++'s"
I do know Objective C uses ARC, and ARC enables us to avoid destroying an object that is still being referenced by something else (meaning, its still needed). But I can't find any drawbacks at all, anywhere. I can only think of "There are no drawbacks" as an answer, but since the question explicitly asks for drawbacks, I'm guessing there must be at least one.
Reference counting may solve a problem that you don't have. It comes at a price, and you'll end up paying the price no matter whether you wanted the solution in the first place.
Contrary to what the gut feeling may say, most objects actually don't need to be shared at all and have a well-defined, unique ownership throughout their life. All that's needed is the ability to pass those objects around; reference counting provides that, but it provides much more, and has a greater cost.
(This answer compares reference counting in Objective C to C++-style lifetime management. It does not consider whether reference counting in Obj-C is sensible in the first place. ARC is simply an automated form of MRC, and if you were using MRC in the past and it made sense, then the question whether to migrate to ARC is not the point of this post. Rather, this post applies equally to the comparison of "MRC in Obj-C vs C++".)
Reference counting 'frees' you from always thinking about WHEN to delete an object. Anybody using the object just says, I still need it (want to retain it) or I am done with it (I release it)
that makes memory management way easier and also makes the code more manageable
BUT
it comes at the price of 2 additional method calls whenever you pass stuff around: you have to retain the object, THEN save the pointer and later also call release it.
When you deal with LOTS of objects that become a real life problem. Just the extra calls can kill your algorithms performance
and especially if you don't need any reference counting because the scope where the object is used is clear, the overhead is just annoying.
so it is convenience + maintainability vs. speed

What could possibly go wrong modifying NSMutableArray from multiple threads without synchronizing access to it? [duplicate]

This question already has answers here:
What happens if NSMutableArray is modified by multiple threads at the same time? (if the objects it contains are retained elsewhere)
(3 answers)
Closed 9 years ago.
I have an NSMutableArray and I am accessing / modifying it from multiple threads. Currently I am doing:
#synchronized(self.items)
{
[self.items addObject:anItem];
}
I am wondering if I don't synchronize access to it, what would potentially go wrong? Or is the behaviour undefined ?
Thanks!
You could, for example, be iterating over it on one thread, and either adding to or removing from it at the same time on another thread - changing values you've already passed over or missing values. If you're lucky it will cause an exception to be raised. If you're unlucky, it could corrupt your data.
It could potentially cause memory leaks as well if two threads try to add to it at the same time. It's possible that the add could succeed on one thread, while also knocking out all reference to the the add on the other thread.
The details of what can go wrong depend on the implementation, which is probably not public. (Or is it available in the Darwin source?) But think about it this way - the implementation probably involves an array or similar structure that keeps track of how many items there are and has pointers to them. Each item has a reference count which must be > 0 when in the array. All of those bits of data could potentially end up in a bad state if 2 threads are modifying them at the same time.

using ARC and not caring about manual memory mgmt anymore [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
When one uses ARC, this means we can forget about memory management related tasks right? e.g., like deletion/release of the memory we allocated etc.
Two places I know we may need to interfere is retain cycles, and one should use __weak before Outlet ivars in class definitions (if these outlets are not top objects in object hierarchy of the XIB).
Is there something else I have to consider?
Things have changed.
You should still stick to some pattern related to memory managment / ARC. You won't retain, release, autorelease and dealloc any more.
New:
You would still overwrite a dealloc method and nil all strong references. That is not really required but can be done. But you would not call [super dealloc] any more.
You will declare properties as strong or weak depending on whether you take ownership or not.
If you want to get rid of an object in a way that the memory is freed up, then you have to nil all strong references to that very object. Each strong reference corresponds to one retain. But you cannot call retain on those objects.
You cannot call undeclared methods any more (Without ARC this will generate a compiler warning, with ARC it is an error.)
You get warnings when using variable selectos (That is using variables of SEL type and perform those on objects) and you should never do that with methods that might have an implact on the retain count (such as alloc).
And you still have plenty of chances of making errors when you interface with areas of the framework that do not ARC, such as core functions.
So it is far away from "forget about" but applying the ARC patterns is less work and less error prone than the former MRC patterns.
When using ARC you dont have to use dealloc/autorelease. so, YES you can forget deletion release etc.
The only thing to consider is strong reference cycles, like the one you mentioned here.
Another example is when you use delegate objects.
You can also refer apple's documentation

Objective C not throwing enough errors? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm new with Objective C and am not an uber programmer anyway but one thing I find odd is that it won't throw errors sometimes when objects are declared not initialized.
I just ran into this again - I had some setup stuff to be done in so I put it in an init function - but the class is a UIViewController that is wired up in the storyboard. So init was never called - and that's my error - (lots of NSObject derived classes in the project and I rushing and just tossed that in to test some things).
But my methods that were making calls to the instance that was supposed to have been set up in int didn't throw errors - it just that the values I was expecting were nil.
Isn't that sort of odd that that sort of stuff would fail silently?
You've got two separate issues here, both quite common for beginners.
Your init was never called because it's the wrong method entirely. It's not the designated initializer for a view controller, and in any case a view controller from a nib or storyboard gets initWithCoder:. So it's up to you to have a sense of what method will be called and when.
Messages to nil return nil with no error. This is a deeply entrenched feature of Objective-C and isn't going to change. There is often quasi-religious debate about it, and there are some clever ways around it, but that's neither here nor there really. Basically it's up to you to use lots of NSLog and lots of nil-checking (NSAssert is a great thing to use for this), especially during early stages.
Not odd at all. That's how Objective-C has always worked. Messages to nil simply do nothing.
It is strange, but that's how Obj-C was designed. Actually, from Obj-C perspective, the code did not fail (silently). Everything was correct.
In Obj-C you can alwyas send messages to ("call methods on") nil.
init is just another message ("method"), not a constructor. It's not needed to create and use an object. You can understand Obj-C only as a thin layer over C language. C language won't report if you haven't called a function on a struct, either.

Implicit data members for #synthesize - good practice or bad habit? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Today, I got a link to a long list of coding guidelines, proclaiming to be "code commandments". A good read, and full of new insights to me. Among the list, somewhere along 25% of the scrollbar, I come across something new to me: Implicit data member creation.
Although every tutorial, book and video I've read or watched about Objective-C always performs the triad of NSNumber *number | #property NSNumber *number | #synthesize number, these commandments now tell me I can simply omit the first step (data member declaration in the interface) because #synthesize will create one on the fly. Say what!?
With a little disbelief I deleted several of my data member declarations, and indeed, my app still works like a charm. Less typing, less reading, less chance for typos.
Sounds to me like a win-win-win, but is it really good practice?
I'm asking this question out of pure disbelief that all the tutorials, books and videos are teaching the wrong lesson, at least too much of it, or that I've been not paying attention in class...
Cheers,
EP.
Edit: Although I copied the expression "data member" from the linked post, it is more commonly described with the word "ivar", just a good one to have in here for search friendliness. This also takes care of my former confusion over property/ivar/member naming :).
Synthesized instance variables are a feature of the modern Objective-C 2.0 runtime. This means they're available on x86_64, on ARM, and as of Xcode 3.2, on the iPhone Simulator. It means exactly what you suggested - you can omit the ivar declaration, and the #synthesize line will generate the ivar for you. The performance of this is exactly the same as declaring the ivar explicitly, but it has the very important benefit of not polluting your header file with private implementation details.
I have begun the practice of removing synthesized properties from the Objective-C classes I create. The primary reason for this is because there is a distinct difference between:
self.myNSObject = [NSObject new];
and
myNSObject = [NSObject new];
Specifically, if myNSObject is declared as a #property(retain, ...) the former line will result in a retainCount of 2 while the latter will result in a retainCount of 1. This means that unless you are extremely careful about every assignment to myNSObject you run the risk of getting your retain/release balancing wrong.
The other reasons you specify are also very valid. There is a lot going on in the synthesized routines that my brain doesn't account for when I'm reading the code I've written, so a lot is taking place behind the scenes that I'm not thinking of yet am accountable for. It's for very a similar reason I've abandoned Apple's Interface Builder.