supportsWeakPointers vs objc_arc_weak_unavailable - objective-c

I think that both methods are equivalent.
Do you know the difference?
objc_arc_weak_unavailable objc_arc_weak_unavailable attribute on
the class's interface declaration. A retainable object pointer type is
weak-unavailable if is a pointer to an (optionally protocol-qualified)
Objective-C class T where T or one of its superclasses has the
objc_arc_weak_unavailable attribute. A program is ill-formed if it
applies the __weak ownership qualifier to a weak-unavailable type or
if the value operand of a weak assignment operation has a
weak-unavailable type.
supportsWeakPointers If you you [sic] find that you must
implement custom retain or release methods, then you must also
implement the following method in your class:
-(BOOL)supportsWeakPointers { return NO; }
This method will prevent weak pointers from being formed to your objects. You are strongly encouraged to find a solution that doesn’t
require implementing your own retain and release methods instead of
doing this.
Note: By checking the LLVM parser I found that the right symbol is objc_arc_weak_reference_unavailable, that is:
__attribute__((objc_arc_weak_reference_unavailable))
#interface Point : NSObject
#end

Significantly, objc_arc_weak_unavailable is a compile time option (you can also declare it using NS_AUTOMATED_REFCOUNT_WEAK_UNAVAILABLE) whereas supportWeakPointers is a runtime call. This question addresses why you might use this.

Related

RLMArray property declaration syntax

When declaring an RLMArray, what is the significance of the second set of brackets? Realm is the only place I've seen this used.
#property NSArray<NSDictionary*> *dictionaries; // I understand this (and it's wonderful!)
#property NSDictionary<NSString*, NSArray<NSString*>*> *dictionaryOfArraysOfStrings; // No problem with this either
#property RLMArray<Object*><Object> *objects; // What is <Object> for?
The two sets of angle brackets are for Objective-C generics and protocols respectively. Objective-C generics lets the compiler know that methods like -[RLMArray firstObject] return the specific type of object that the array contains, rather than any possible RLMObject subclass. Sadly this extra type information is erased at runtime, so Realm has no way to tell from the use of Objective-C generics alone in the property declaration what type of object the array contains. This is where the protocol conformance comes in. The protocol that a property conforms to is available to Realm at runtime, and so is used to inform Realm of the object type that your RLMArray property will contain. Realm provides the RLM_ARRAY_TYPE macro to declare a protocol of the same name as a model class, so it is easy to miss that a protocol is involved.

When to use [self.obj message] vs [obj message] [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
When to access properties with 'self'
In Objective-C on iOS, what is the (style) difference between “self.foo” and “foo” when using synthesized getters?
For example sake, I have a #property named obj and I #synthesize it. So when do I need to use [self.obj message] vs [obj message] in my implementation class.
Using self, the getter method will be called. Thus, any additional logic in this getter method is executed. This is especially useful when instance variables are lazy loaded through their getters.
I myself try to use self most of the time. Lazy loading is just an example, another thing is that with self, subclasses may override the getter to get different results.
Using self to set a variable is even more useful. It will trigger KVO notifications and handle memory management automatically (when properly implemented, of course)
Here are two great tutorials that cover this issue well:
Understanding your (Objective-C) self
When to use properties & dot notation
When synthesize a property, the compiler declare a related ivar for you, in default, the ivar is the same as property name. I recommend use self.obj always to keep code cleaner, and avoid some potential bugs.
And I suggest you follow the good practice from Apple, #synthesize obj=_obj, the ivar will become _obj, when you mean to use property, this style force you to write self.obj, directly call obj will be error since the ivar is _obj.
Edit: automatically creating ivar for property is only in modern Objective-C runtime, it's safe in iOS SDK 4.0 and Mac OS X 10.6 above.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html%23//apple_ref/doc/uid/TP30001163-CH17-SW1
For #synthesize to work in the legacy
runtime, you must either provide an
instance variable with the same name
and compatible type of the property or
specify another existing instance
variable in the #synthesize statement.
With the modern runtime, if you do not
provide an instance variable, the
compiler adds one for you.
In the future, please search the site. You'll often find that the exact question you're asking has been asked before:
difference between accessing a property via "propertyname" versus "self.propertyname" in objective-c?
When to access properties with 'self'
self.variable and variable difference
Objective-C: When to call self.myObject vs just calling myObject
iVar property, access via self?
Should I Use self Keyword (Properties) In The Implementation?
In Objective-C on iOS, what is the (style) difference between "self.foo" and "foo" when using synthesized getters?
When to use self on class properties?
... etc.

How does dot syntax work without explicit #property in Objective-C?

I wrote a setter and getter method following Apple's conventions and noticed that despite having no variable I can still access the setter and getter using the dot syntax. Is this normal behavior? What enables this feature?
Example:
// Header definition. Keep in mind there is no class variable or #property for height.
- (void)setHeight:(float)height;
- (float)height;
// else using the dot syntax.
object.height = 10.0f;
A property-access expression is equivalent to a message expression:
[object setTexture:tex];
A property declaration is equivalent to one (readonly) or two (readwrite/default) instance-method declarations. Keywords like retain tell the compiler how to implement the method if you tell it to do so (#synthesize).
However, you can skip the property declaration and declare the methods directly, as shown in your question. You can't synthesize their implementations, since you need a property declaration for that (otherwise, it wouldn't know what memory-management policy to use: assign, retain, or copy), but you can always implement the methods yourself.
Then, even though you declared and implemented the methods yourself, since property-access syntax and message syntax are equivalent to each other, you can use the methods whichever way you want: With a message expression, or with a property-access expression.
Some would consider it bad form, though, to use property access expressions on anything but a formal #property (e.g., myString.length or myArray.count or myView.frame). It definitely is bad form to use a property-access expression to send a message that doesn't access any kind of property; foo.retain.autorelease, for example, is bad and wrong: It reeks of trying to pretend you're programming some other language than Objective-C.
Incidentally, a property and a variable are unrelated. A #property will ordinarily be backed by an instance variable, but this is not required: You could store the property's value inside another object, or convert it to and from some other format, or both. Likewise, accessing a property (which is an accessor message) and accessing an instance variable (which is just accessing a variable, nothing more) are very different.

What is the different between an id and NSObject in Objective C?

What is the different between this:
id:
#import <objc/Object.h>
#interface Forwarder : Object
{
id something;
}
NSObject:
#import <objc/Object.h>
#interface Forwarder : Object
{
NSObject *something;
}
Thz u.
This Greg MILLER's blog post from the unixjunkie blog sums up the differences
Some extracts:
There's often confusion about the difference between the following three declarations in Objective-C:
id foo1;
NSObject *foo2;
id<NSObject> foo3;
The first one is the most common.
It simply declares a pointer to some Objective-C object (see /usr/include/objc/objc.h). id gives the compiler no information about the actual type of the object, so the compiler cannot do compile-time type checking for you.
Just because we know that an id is an Objective-C object does not mean that it points to an object that derives from NSObject, or that it even has common methods like retain and release.
One solution is to statically type our variable using NSObject* as shown in number 2 above.
This gives the compiler information about the class of the object pointed to by foo2 so the compiler can warn if you send a message to foo2 that an NSObject doesn't respond to. This means you can safely call retain, release, description, etc., but the compiler will warn if you call length or count or anything that an NSObject doesn't respond to.
Declaring an object as id<NSObject> tells the compiler that you don't care what type the object is, but you do care that it conforms to the specified NSObject protocol**.
** the protocol (#protocol) named NSObject. There is also a class named NSObject that does indeed conform to the NSObject protocol, but they are two different thing
The compiler will ensure that all objects you assign to that pointer conform to the required protocol.
A pointer typed like this can safely hold any NSObject (because NSObject conforms to the NSObject protocol), but it could also hold any NSProxy, because NSProxy also conforms to the NSObject protocol.
In english, the declaration id<NSObject> foo3; says "foo3 is a pointer to an object of any type that behaves like an NSObject".
This is very powerful, convenient, and expressive. In reality, we often don't care what type an object is, we just care that it responds to the messages that we want to send it (e.g., retain, release).
If you don't want (or can't have) any type checking, then use a plain id. This is very common for return types on methods that don't know the type of object they're returning (e.g., +alloc). It is also common to declare delegates to be type id, because delegates are generally checked at runtime with respondsToSelector:, and they usually aren't retained.
However, if you do want compile-time type checking, you must decide between the second and third cases. Well, let me just help you out—you want the third case! :-) I've very, very, VERY rarely seen a situation where NSObject * worked but id would not. And using the protocol form has the advantage that it will work with NSProxys.
The practical difference is that you do not need to typecast an id, but you usually need to typecast an NSObject * to something before using it. NSObject is the base class that almost all other classes are derived from where id is more of a language keyword.
An id responds to any method without a compiler warning; NSObjects only respond without warning to methods defined in NSObject, including the NSObject protocol.

Using instance variables with Modern Runtime

I have several years of experience in Obj-c and Cocoa, but am just now getting back into it and the advances of Obj-C 2.0 etc.
I'm trying to get my head around the modern runtime and declaring properties, etc. One thing that confuses me a bit is the ability in the modern runtime to have the iVars created implicitly. And of course this implies that in your code you should always be using self.property to access the value.
However, in init* and dealloc(assuming you're not using GC) methods we should be using the iVar directly (in the current runtime).
So questions are:
Should we use property accessors in init* and dealloc with Modern Runtime?
If so, why is this different? Is it just because the compiler can't see the iVar?
If I need to override an accessor, can I still access that iVar that will be defined at runtime or do I have to define an actual iVar that the runtime will then use?
Again, if I can access the synthesized iVar, why can't I continue to do this for the init* and dealloc methods?
I read the docs several times, but they seemed a bit vague about all of this and I want to be sure that I understand it well in order to decide how I want to continue coding.
Hope that my questions are clear.
Quick summary of testing:
If you don't declare the ivar in legacy, compiler is completely unhappy
If you use #ifndef __OBJC2__ around ivar in legacy compiler is happy and you can use both ivar directly and as property
In modern runtime, you can leave the ivar undefined and access as property
In modern runtime, trying to access ivar directly without declaration gives error during compile
#private declaration of ivar, of course, allows direct access to ivar, in both legacy and modern
Doesn't really give a clean way to go forward right now does it?
In the current (OS X 10.5/GCC 4.0.1) compiler, you cannot directly access the runtime-synthesized ivars. Greg Parker, one of the OS X runtime engineers put it this way on the cocoa-dev list (March 12, 2009):
You can't in the current compiler. A
future compiler should fix that. Use
explicit #private ivars in the
meantime. An #private ivar should not
be considered part of the contract -
that's what #private means, enforced
by compiler warnings and linker
errors.
And why isn't there a way to
explicitly declare instance variables
in the .m file for the new runtime?
Three reasons: (1) there are some
non-trivial design details to work
out, (2) compiler-engineer-hours are
limited, and (3) #private ivars are
generally good enough.
So, for now you must use dot-notation to access properties, even in init and dealloc. This goes against the best practice of using ivars directly in these cases, but there's no way around it. I find that the ease of using runtime-synthesized ivars (and the performance benefits) outweigh this in most cases. Where you do need to access the ivar directly, you can use a #private ivar as Greg Parker suggests (there's nothing that prevents you from mixing explicitly declared and runtime-synthesized ivars).
Update With OS X 10.6, the 64-bit runtime does allow direct access to the synthesized ivars via self->ivar.
Since instance variables themselves can only be synthesized in the modern runtime (and must be declared in the #interface under 32-bit or pre-Leopard), it's safest / most portable to also declare the ivar
Should we use property accessors in init* and dealloc with Modern Runtime?
My rule of thumb is "possibly" for -init*, and "usually not" for -dealloc.
When initializing an object, you want to make sure to properly copy/retain values for ivars. Unless the property's setter has some side effect that makes it inappropriate for initialization, definitely reuse the abstraction the property provides.
When deallocating an object, you want to release any ivar objects, but not store new ones. An easy way to do this is to set the property to nil (myObject.myIvar = nil), which basically calls [myObject setMyIvar:nil]. Since messages to nil are ignored, there is no danger in this. However, it's overkill when [myIvar release]; is usually all you need. In general, don't use the property (or directly, the setter) in situations where deallocation should behave differently than setting the variable.
I can understand eJames' argument against using property accessors in init/dealloc at all, but the flipside is that if you change the property behavior (for example, change from retain to copy, or just assign without retaining) and don't use it in init, or vice versa, the behavior can get out of sync too. If initializing and modifying an ivar should act the same, use the property accessor for both.
If so, why is this different? Is it just because the compiler can't see the ivar?
The modern runtime deals with class size and layout more intelligently, which is why you can change the layout of ivars without having to recompile subclasses. It is also able to infer the name and type of the ivar you want from the name and type of the corresponding property. The Objective-C 2.0 Runtime Programming Guide has more info, but again, I don't know how deeply the details explained there.
If I need to override an accessor, can I still access that iVar that will be defined at runtime or do I have to define an actual iVar that the runtime will then use?
I haven't tested this, but I believe you're allowed to access the named ivar in code, since it actually does have to be created. I'm not sure whether the compiler will complain, but I would guess that since it will let you synthesize the ivar without complaining, it is also smart enough to know about the synthesized ivar and let you refer to it by name.
Again, if I can access the synthesized iVar, why can't I continue to do this for the init* and dealloc methods?
You should be able to access the property and/or ivar anytime after the instance has been allocated.
There is another SO question with similar information, but it isn't quite a duplicate.
The bottom line, from the Objective-C 2.0 documentation, and quoted from Mark Bessey's answer is as follows:
There are differences in the behavior that depend on the runtime (see also “Runtime Differences”):
For the legacy runtimes, instance variables must already be declared in the #interface block. If an instance variable of the same name and compatible type as the property exists, it is used—otherwise, you get a compiler error.
For the modern runtimes, instance variables are synthesized as needed. If an instance variable of the same name already exists, it is used.
My understanding is as follows:
You should not use property accessors in init* and dealloc methods, for the same reasons that you should not use them in the legacy runtime: It leaves you open to potential errors if you later override the property methods, and end up doing something that shouldn't be done in init* or dealloc.
You should be able to both synthesize the ivar and override the property methods as follows:
#interface SomeClass
{
}
#property (assign) int someProperty;
#end
#implementation SomeClass
#synthesize someProperty; // this will synthesize the ivar
- (int)someProperty { NSLog(#"getter"); return someProperty; }
- (void)setSomeProperty:(int)newValue
{
NSLog(#"setter");
someProperty = newValue;
}
#end
Which leads me to think that you would be able to access the synthesized ivar in your init* and dealloc methods as well. The only gotcha I could think of is that the #synthesize line may have to come before the definitions of your init* and dealloc methods in the source file.
In the end, since having the ivars declared in the interface still works, that is still your safest bet.
I am running into the same problem. The way I am working around not being able to access the synthesized instance variables is the following:
public header
#interface MyObject:NSObject {
}
#property (retain) id instanceVar;
#property (retain) id customizedVar;
#end
private header / implementation
#interface MyObject()
#property (retain) id storedCustomizedVar;
#end
#implementation MyObject
#synthesize instanceVar, storedCustomizedVar;
#dynamic customizedVar;
- customizedVar {
if(!self.storedCustomizedVar) {
id newCustomizedVar;
//... do something
self.storedCustomizedVar= newCustomizedVar;
}
return self.storedCustomizedVar;
}
- (void) setCustomizedVar:aVar {
self.storedCustomizedVar=aVar;
}
#end
It's not that elegant, but at least it keeps my public header file clean.
If you use KVO you need to define customizedVar as dependent key of storedCustomizedVar.
I'm relatively new to Obj-C (but not to programming) and have also been confused by this topic.
The aspect that worries me is that it seems to be relatively easy to inadvertently use the iVar instead of the property. For example writing:
myProp = someObject;
instead of
self.myProp = someObject;
Admittedly this is "user" error, but it's still seems quite easy to do accidentally in some code, and for a retained or atomic property it could presumably lead to problems.
Ideally I'd prefer to be able to get the runtime to apply some pattern to the property name when generating any iVar. E.g. always prefix them with "_".
In practice at the moment I'm doing this manually - explicitly declaring my ivars, and deliberately giving them different names from the properties. I use an old-style 'm' prefix, so if my property is "myProp", my iVar will be "mMyProp". Then I use #synthesize myProp = mMyProp to associate the two.
This is a bit clumsy I admit, and a bit of extra typing, but it seems worth it to me to be able to disambiguate a little bit more clearly in the code. Of course I can still get it wrong and type mMyProp = someObject, but I'm hoping that the 'm' prefix will alert me to my error.
It would feel much nicer if I could just declare the property and let the compiler/runtime do the rest, but when I have lots of code my gut instinct tells me that I'll make mistakes that way if I still have to follow manual rules for init/dealloc.
Of course there are also plenty of other things I can also do wrong...