Best way of declaring private variables in cocoa - cocoa

I would like to know what the recommendations are for declaring private instance variables in cocoa. This question is in the context of developing apps on the iPhone.
I am aware of at least three ways of declaring private variables:
Declare them in the interface of the h file with the modifier #private:
#interface MyClass : NSObject {
#private
NSObject * myPrivateVar;
}
Declare them in the implementation section of the m file:
#implementation MyClass
NSObject * myPrivateVar;
Declare a property in the interface of the m file (not even declaring the variable itself):
#interface MyClass ()
#property (nonatomic, retain) NSString* myPrivateVar;
#end
#implementation
#synthesize myPrivateVar;
So far, I have used extensively 2 but recently came to realize this might be dangerous due to the lack of garbage collection. Are there cases where it remains perfectly acceptable to use that method?
Is 3 more appropriate? Does the answer depend on the object type (e.g. mutable/immutable)?
Pointers to reference material discussing the trade offs for using/not using properties in general also appreciated.

Your three options have different semantics:
This creates an instance variable. Without garbage collection you need to retain/release objects you store into myPrivateVar.
This does not define an instance variable at all. Variables defined outside of the #interface and the scope of many method (or function) definitions are "global" - effectively class variables (which Objective-C has no special syntax for). Such a variable is shared by all instances of MyClass.
The difference between using a property (with or without the variable being explicitly declared) comes down to memory management. Defined as you have with retain means that there is no need for retain/release when you do not have garbage collection.
So don't use 2! Option 3 clearly has benefits if you don't have garbage collection, it provides some measure of abstraction over option 1, and is more costly - though you will probably not notice the difference outside of computationally intensive code which access the variable heavily.
Update 2015
Where garbage collection is used above ARC (automatic reference counting) is now more applicable (garbage collection is now deprecated). Also there is now a fourth option:
Declare them in the implementation section of the m file:
#implementation MyClass
{
NSObject * myPrivateVar;
}
Unlike option (2) this does declare an instance variable. The variable is private to the implementation, and with ARC memory management is automatic. The choice between this and (3) [which incidentally also no longer requires the #synthesize] comes down to choice and need; properties give you dot syntax, the ability to customise the setter and/or getter, and the copy attribute for automatic copy on assignment, but if you need none of these you can simply use the an instance variable.

Related

iOS 10 NSNumber crash with enumerations

I am having a very weird issue relating to NSNumber objects for my enumerated values and access to them on a device running iOS os version 10.
Just as a disclaimer - this issue does not happen in other iOS os versions.
I have declared an enum like so:
typedef NS_ENUM(NSInteger, MYENUM) {
FIRST = 1500,
SECOND = 1700,
THIRD = 1900,
...
};
When using this enum, I am passing it along in this fashion:
[[MyObject alloc] initObjectWith:#(FIRST)];
Excluding the inner logic, I am using the enum in a dictionary and thus need to convert it to a NSNumber.
While doing so, the application crashes, because the enum is somehow not a NSNumber, but rather a NSIndexPath.
Why does this happen?
When I remove the boxed literal and change the method signature to accept a NSInteger, this crash disappears.
I have tried searching online for this type of issue, but have come up short.
Further Explanation (per comment)
No special logic happens inside the init method for myObject, just assigning the property which is defined as a NSNumber to the parameter that is passed.
Regarding the crash log, Xcode is infamous in providing not so useful crash logs and all I am seeing is EXC_BAD_ACCESS, which could either mean accessing an object that has been released or a potential memory leak.
The MyObject class is defined as follows:
header file:
#interface ISNEvent : NSObject
#property(nonatomic, assign) NSNumber* number;
-(instancetype)initObjectWith:(NSNumber*)number;
#end
.m file:
- (instancetype)initObjectWith:(NSNumber*)number {
self = [super init];
if (self) {
_number = number;
}
return self;
}
You have defined your property with assign memory semantics:
#property(nonatomic, assign) NSNumber* number;
That means that you’ll get a reference to whatever you supply, but you won’t keep a strong reference and you won’t nil your reference when the object is deallocated. That’s the worse of both worlds, because you’re keeping a dangling reference to an object that you’re allowing to be deallocated. As you said, this particular error “could ... mean accessing an object that has been released”, and that’s precisely what’s going on here.
You might consider temporarily turning on zombies (command+<) or “Product” » “Scheme” » “Edit Scheme...” and go to the “Diagnostics” section of the “Run” settings, and see if your behavior changes. You’ll probably no longer see that NSIndexPath (or whatever) reference, but rather some confirmation that the NSNumber instance has been deallocated.
Anyway, you undoubtedly meant to make this NSNumber property a strong reference:
#property(nonatomic, strong) NSNumber *number;
The other solution would be to make it weak, allowing it to be deallocated, but safely setting your reference to nil. That’s safer than assign, but I also doubt that’s what you intended. And the third alternative would be copy, which is what we sometimes use with mutable types, which isn’t applicable here.
Bottom line, nowadays, I’d advise against ever using assign memory semantics with any object types. Use strong, copy, or weak. In this case, strong is what you want. Only use assign with primitive data types (e.g. NSInteger, CGFloat, etc.), but not with object types.
And, remember, when you’re done testing with the zombies, turn that diagnostic feature off.

Why use delegate and protocol instead of just passing an instance in Swift?

I was trying to pass around variables between views in Swift, and ran into the rather abstract concept of protocols and delegates.
Then I tried storing a reference to the first view in a second view and call functions on that directly. This seems to work:
SCREEN 1
class Screen1: UIViewController {
var myName = "Screen1"
override func viewDidLoad() {
super.viewDidLoad()
}
//
// checking if the segue to screen 2 is called and then passing a reference
//
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "screen2Segue"{
let vc = segue.destinationViewController as Screen2
vc.storedReference = self
}
}
func getName() -> String {
return myName
}
}
SCREEN 2
class Screen2: UIViewController {
var storedReference:Screen1!
override func viewDidLoad() {
super.viewDidLoad()
}
func testReference() {
// calling a function on the stored reference to screen 1
var str = storedReference.getName()
println("Leaving screen 2, going to " + str)
}
}
My question: what's wrong with this code? Why use delegates and protocols if you can just pass around a reference directly?
Perhaps related: when does a view get un-initialized and replaced by an entirely new view instance? Am I calling 'getName()' on an old instance?
Protocols are useful for separating implementation from interface, which helps increase code reusability, understandability, and testability.
For example, perhaps you wish to store items in a List of some sort. Some possible implementations of a List include array-based implementations and node-based (linked-list) implementations. If you were to declare a protocol called List and have classes ArrayList and LinkedList that implemented that protocol, anything that required the use of a list (variable passed as a parameter to a method, a property, etc) could use List as the variable type, and be able to function without caring about whether a the list was an ArrayList or a LinkedList. You could change which type was used, or how they were implemented, and it would not matter to whatever was using them, because only the exposed interface declared in the protocol would be visible.
Protocols can also be useful for emulating something like multiple inheritance, as a class can inherit from a superclass, as well as implement one or more interfaces. (eg. A bat is both a mammal and winged, so it could be represented as a Bat class inheriting from a Mammal class that implements the Winged protocol).
The delegate pattern uses protocols to delegate some responsibilities to another object, which is especially good for code separation and reusability. For example, the UITableViewDelegate protocol in iOS allows a UITableView to react to things like cell selection by delegating another object to handle the event. This has probably been used by millions of objects in thousands of applications, without the developers at Apple who implemented UITableView and UITableViewDelegate having ever known anything about the objects that were implementing the protocol.
By directly passing a reference between your view controllers, you are forcing the second to be completely dependent upon the first. If you ever wished to change the flow of your application so that the second view controller could be accessed from somewhere else, you would be forced to rewrite that view controller to use the new origin. If you use a protocol instead, no changes to the second view controller would have to be made.
It is a basic design principle to not expose any more of a design than you have to. By passing the reference around you are exposing the whole object. Which means that others can call any of its functions and access any of its properties. And change them. This isn't good. Besides letting others use the object in ways it might not have intended, you will also run into issues if you try to change the object in the future and find out that it breaks somebody else who was using something you didn't intend. So, always a good idea to not expose anything that you don't have to. This is the purpose of delegates and protocols. It gives the object complete control over what is exposed. Much safer. Better design.
I think you didn't fully get the understanding what protocols are.
I always say protocols are like contracts.
The delegate object that implements a certain protocols promises that it can do things the delegator can't do.
In real world I have a problem with my house's tubes.
I (the delegator) call a plumber (the delegate) to fix it. The plumber promises (by contract) to be able to duo it. The promise is the protocol. I don't care how he do it, as long as he does it.
But these contracts are not only useful for delegation.
I am just writing a food ordering app. As it has a menu it need item to display in it.
I could go with basic inheritance and write a class MenuItem, that all sub classes must inherit from.
Or I write an protocol to express: «No matter what object you are, as long as you fulfill this contract we have a deal». this allows me to create many different classes or annotate existing classes in categories, although I don't have the tool of multiple inheritance.
Actually I do both: I write a protocol MenuItem and a class MenuItem that conforms to the protocol. Now I can use simple inheritance or use classes that do not inherit from the class MenuItem.
Code in Objective-C (sorry: I am still transitioning to Swift)
#protocol MenuItem <NSObject>
-(NSString *)name;
-(double) price;
-(UIColor *)itemColor;
#end
#interface MenuItem : NSObject <MenuItem>
#property (nonatomic, copy) NSString *name;
#property (nonatomic, assign) double price;
#property (nonatomic, strong) UIColor *itemColor;
#end
#import "MenuItem.h"
#implementation MenuItem
-(id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if (self) {
self.name = [decoder decodeObjectForKey:#"name"];
self.price = [decoder decodeDoubleForKey:#"price"];
self.itemColor = [decoder decodeObjectForKey:#"itemColor"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeDouble:self.price forKey:#"price"];
[encoder encodeObject:self.name forKey:#"name"];
[encoder encodeObject:self.itemColor forKey:#"itemColor"];
}
#end
Apple uses the same Architecture for NSObject: there is a protocol and a class NSObject. This allows classes, that aren't intact inheriting from the class NSObject to act ash an NSObject. One famous example:NSProxy.
in your case Screen1 promises to be able to understand messages that are send by the detail view controller Screen2. These allows decoupling: any object that does understand Screen1's protocol can be used. Also it helps to maintain a sane object tree, as we don't have to have circular imports. But in general you have to keep in mind that the delegator (Screen2) must keep a weak reference to it's delegate, otherwise we have a retain circle.
Of course an important example it UITableView:
The table view object knows everything about rendering it's cells, handling scrolling and so one. But the engineer who wrote it couldn't now how you want your table view look like. That's why he introduced a delegate to give you the chance to create the right cell. As he couldn't also know what your data looks like, he also introduced the datasource - that works exactly like a delegate: you will be asked to provide all information about your data, that are needed.
This is mostly a matter of opinion so this question should probably be closed, but I think the developer community as a whole is in an agreement on this so I am going to answer it anyway.
An important concept in Software Architecture (the design of the structure of code) is called Separation of Concerns. The basic principle is that you should break down what your code has to do into small components that only have one distinct purpose. Each of these components should be able to stand mostly on their own without much concern with other components other than the ones it needs to directly be interacting with.
This helps greatly with code reuse. If you design a small component that is independent of most / if not all other components, you can easily plug that into other parts of your code or other applications. Take UITableView for example. By using the delegate pattern, every developer can easily create a table view and populate it with whatever data they want. Since that data source is a separate object (with the separate concern of coming up with the data) you can attach that same data source to multiple table views. Think of a contact list on iOS. You will want to access that same data in many ways. Instead of always rewriting a table view that loads the specific data and displays it in a specific way, you can reuse the data source with a different table view as many times as you want.
This also helps with the understandability of your code. It is tough for developers to keep too many thing in their head about the state of your app. If each of your code components are broken down into small, well defined responsibilities, a developer can understand each component separately. They can also look at a component, and make accurate assumptions about what it does without having to look at the specific implementation. This isn't such a big deal with small apps, but as code bases grow, this becomes very important.
By passing in a reference to your first view controller, you are making your second view controller completely dependent on the first. You cannot reuse the second view controller in another instance and its job becomes less clear.
There are lots of other benefits to separation of concerns but I believe those are two compelling and important ones.
I think the problem with the latter arises with multiple reuse of a single class.
Take for example a custom UITableViewCell called CustomTableViewCell. Let's say you have Class A and Class B which both have tableViews and both would want to use CustomTableViewCell as their cell. You now have two options. Would you rather:
A. Use a delegate/protocol for CustomTableViewCell called CustomTableViewCellDelegate. Declare a single object inside the class CustomTableViewCell named "delegate" which implements the mentioned protocol and call on that regardless of what class it calls on
or
B. Declare an object for each class (Class A, Class B) inside CustomTableViewCell so you can hold a reference to each of them.
If you need to use CustomTableViewCell for a number of classes, then I think you know which option to take. Declaring multiple objects for different classes inside CustomTableViewCell would be a pain to see from a software architecture standpoint.

Accessing an NSMutableArray inside my custom object

I'm sure this is an complete Noob question... but I've actually never had to deal with this scenario before so I'm a bit befuddled...
Let's say I have a custom object I'll call person, and each person object can have an array of "possessions", a kind of inventory if you will. I would set it up like this:
interface person : NSObject {
NSString *name;
NSMutableArray *posessions;
#property (copy) NSString *name;
#property (copy) NSMutableArray *posessions; // no idea if this is even necessary...
}
Of course, I would also synthesize my properties in the implementation file... Now, in my actual controller object, I would make an instance of my object (or usually an array of instances, but for this example, one will work fine...) as so:
person *aPerson;
I know that to access the persons name, I could make a call like this:
[aPerson setName:#"Bob"];
and to retrieve that name, I might use this:
aVar = [aPerson name];
What I'm stuck on is how exactly would I go about adding or retrieving objects to the NSMutableArray located inside my person class? Let's say I want to use the "count" method for the NSMutable Array.
I've done some trial and error with attempts such as:
[aPerson.posessions count];
[[aPerson posessions] count];
Likewise, to add an object to an array, I have often used:
[someArray addObject:anObject];
but attempts like this haven't worked:
[aPerson.posessions addObject:anObject];
After reading up a bunch and searching the web, I can't seem to find exactly how to interact with this NSMutableArray in my custom class. I'm sure it's something obvious that I'm just not quite getting, and it's become a sort of mental block...
Also, am I correct in synthesizing accessor properties for the NSMutableArray? If so, setX and X don't seem to be quite so obvious with NSMutableArray... unless they simply copy the entire array into a local variable...
Perhaps is this what needs to be done? use the accessor methods to get the entire array, place it in a local variable, make my changes, then use the set accessor method to put the entire array back into my person object?
Can someone enlighten me a bit on the syntax I should be using here?
* EDIT *
I thought I'd add a bit of clarification to this question. My custom objects (in the above example, my person object) are basically database records. I have several databases I am working with in my project, so for example:
Person - a custom sub-class of NSObject containing multiple NSString Objects, as well as Ints and BOOLs.
personDatabase - An Array of Person objects (set up and controlled within my main CONTROLLER object)
All of the set and get methods are called from "Controller".
What I have been attempting to do is to directly access the individual objects contained within the personDatabase from within my Controller object. I have done this by declaring another object this way:
Person *activePerson;
Then, all of my calls are made to the currently active Person record (the one currently selected from the personDatabase), such as:
someOutput = [activePerson name];
etc.
Is there a way to directly access the objects inside the NSMutableArray object inside the activePerson object from my Controller object?
You've specified the 'possessions' property as 'copy'. Therefore, when you write aPerson.possessions you are getting a copy of the possessions array. The call to addObject adds anObject to a new array that is a copy of aPerson's array of possessions. The simplest 'fix' would be to change 'copy' to 'retain' (and probably 'readonly'). [Edit: Wrong; it is 'copy on assign' - not 'copy on read']
However, there is a bigger issues. A person has possessions but how you store them is an implementation detail. When you put NSMutableArray in the public interface you overly restrict your implementation. You might be better served to change the Person interface along the lines of:
#interface Person : NSObject {
#private
NSString *name;
// ...
}
- (Boolean) addPossession: (NSObject *) obj;
- (Boolean) remPossession: (NSObject *) obj;
- (Boolean) hasPossession: (NSObject *) obj;
- (NSArray *) allPossessions;
#end
Then, how you implement these possession methods depends on if you use an array, a set, a linked-list, a tree, a whatever.

Does Objective-C support Mixin like Ruby?

In Ruby, there's Modules and you can extend a class by "mixing-in" the module.
module MyModule
def printone
print "one"
end
end
class MyClass
include MyModule
end
theOne = MyClass.new
theOne.printone
>> one
In Objective-C, I find that I have a set of common methods that I want a number of Class to "inherit". What other ways can I achieve this without creating a common class and deriving all from that common class?
Shameless plug: ObjectiveMixin
It takes advantage of Objective-C runtime's capability of adding methods to a class in runtime (as opposed to categories, which are compile-time only). Check it out, it works pretty good and in a similar fashion to Ruby's mixins.
Edit: changes added because some people feel I am responsible for the limitations of Objective-C.
Short answer: you can't. Objective-C doesn't have the equivalent of Ruby mixins.
Slightly less short answer: Objective-C does have something with arguably the same flavour: protocols. Protocols (Interfaces in some other languages), are a way to define a set of methods an class that adopts that protocols is committing to implementing. A protocol doesn't provide an implementation though. That limitation prevents using protocols as an exact equivalent to Ruby mixins.
Even less short answer: However, the Objective-C runtime has an exposed API that lets you play with the dynamic features of the language. Then you step outside the language, but you can have protocols with default implementations (also called concrete protocols). Vladimir's answer shows one way to do that. At that point it seems to me you get Ruby mixins alright.
However, I am not sure I would recommend doing that. In most cases, other patterns fit the bill without playing games with the runtime. For example, you can have a sub-object that implement the mixed-in method (has-a instead of is-a). Playing with the runtime is OK, but has 2 drawbacks:
You make your code less readable as it requires readers to know a lot more than the language. Sure you can (and should) comment it, but remember that any necessary comment can be seen as an implementation defect.
You depend on that implementation of the language. Sure, Apple platforms are by far the most common ones for Objective-C but don't forget Cocotron or GnuStep (or Etoilé) which have different runtimes, which may or may not be compatible with Apple's on that respect.
As a side note, I state below that categories cannot add state (instance variables) to a class. By using the runtime API, you can lift that limitation too. This is beyond the scope of this answer however.
Long answer:
Two Objective-C features look like possible candidates: categories and protocols. Categories are not really the right choice here, if I understand the question properly. The right feature is a protocol.
Let me give an example. Suppose you want a bunch of your classes to have a specific ability called "sing". Then you define a protocol:
#protocol Singer
- (void) sing;
#end
Now you can declare that any of your own classes adopts the protocol the following way:
#interface Rectangle : Shape <Singer> {
<snip>
#end
#interface Car : Vehicle <Singer> {
<snip>
#end
By declaring that they adopt the protocol they commit themselves to implementing the sing method. For example:
#implementation Rectangle
- (void) sing {
[self flashInBrightColors];
}
#end
#implementation Car
- (void) sing {
[self honk];
}
#end
Then you use those classes for example like this:
void choral(NSArray *choir) // the choir holds any kind of singer
{
id<Singer> aSinger;
for (aSinger in choir) {
[aSinger sing];
}
}
Notice that the singers in the array don't need to have a common superclass. Notice also that a class can have only one superclass, but many adopted protocols. Notice finally that type checking is done by the compiler.
In effect, the protocol mechanism is multiple inheritance used for the mixin pattern. That multiple inheritance is severely limited because a protocol cannot add new instance variables to a class. A protocol only describes a public interface adopters must implement. Unlike Ruby modules it does not contain an implementation.
That's the most of it. Let's mention categories however.
A category is declared not in angle brackets, but between parenthesis. The difference is that a category can be defined for an existing class to expand it without subclassing it. You can even do so for a system class. As you can imagine, it's possible to use categories to implement something similar to mixin. And they were used that way for a long time usually as category to NSObject (the typical root of the inheritance hierarchy), to such an extent that they were called "informal" protocols.
It's informal because 1- no type checking is done by the compiler, and 2- implementing the protocol methods is optional.
There is no need today to use categories as protocols, especially because the formal protocols can now declare that some of their methods are optional with the keyword #optional or required (the default) with #required.
Categories are still useful to add some domain specific behavior to an existing class. NSString is a common target for that.
It's also interesting to point out that most (if not all) of NSObject facilities are in fact declared in a NSObject protocol. This means that it's not really compelling to use NSObject as a common superclass for all classes, though this is still commonly done for historical reasons, and well... because there is no drawback for doing so. But some system classes, such as NSProxy, are not NSObject.
You can literally mixin the code using #include. This is not advisable and is against all the religions in objective-c, however works perfectly.
Please, don't do it in the production code.
for example in the file:
MixinModule.header (should not be compiled or copied to the target)
-(void)hello;
MixinModule.body (should not be compiled or copied to the target)
-(void)hello{
NSLog(#"Hello");
}
in mixin class:
#interface MixinTest : NSObject
#include "MixinModule.header"
#end
#implementation MixinTest
#include "MixinModule.body"
#end
usage case:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]){
#autoreleasepool {
[[[MixinTest new] autorelease] hello];
}
return 0;
}
Please, don't do it in the production code.
This is my take on implementing Mixins in Objective-C, without using the Objective-C runtime directly. Maybe it's helpful to someone: https://stackoverflow.com/a/19661059/171933

Best practice for copying private instance vars with NSCopying

I might be missing something obvious here, but I'm implementing NSCopying on one of my objects. That object has private instance variables that are not exposed via getters, as they shouldn't be used outside the object.
In my implementation of copyWithZone:, I need alloc/init the new instance, but also set up its state to match the current instance. I can obviously access current private state from inside copyWithZone:, but I can't set it into the new object, because there are no accessors for that state.
Is there a standard way around this while still keeping data privacy intact?
Thanks.
First, you should always have getters, even if they're private. Your object should only access even its own ivars using accessors (except in a very small number of cases). This will save you a great deal of suffering over memory management.
Second, Alex's suggestion of using -> is a standard approach, even though this violates the getters rule above. There are a small number of exceptions to that rule, and copy is one of. Using private setters here is still reasonable (and I used to do it that way exclusively), but I've found for various reasons that using -> often works out cleaner.
Be very careful to get your memory management correct. If you need to call [super copyWithZone:], then you should also read up on the complexities of NSCopyObject() and how it impacts you even if you don't use it yourself. I've discussed this at length in "NSCopyObject() considered harmful."
You can access the instance variables of the copy directly. You use the same pointer dereferencing syntax you would use with a struct. So, for example, if your class is this:
#interface MyCopyableClass : NSObject {
int anInstanceVariable;
}
#end
You can do this:
- (id)copyWithZone:(NSZone *)zone {
MyCopyableClass *theCopy = [[[self class] allocWithZone:zone] init];
theCopy->anInstanceVariable = anInstanceVariable;
return theCopy;
}
One option is to create a custom initializer that accepts the private iVar values. So you create it like:
-(id) initWithPropertyOne:(SomeClass *) anObject andPropertyTwo:(SomeClass *) anotherObject;
When you instantiate the copy, just use the custom initializer.

Resources