Having to cast to id to invoke isKindOfClass - objective-c

In the following code
id<SwiftProtocol> anotherInstanceAsProtocol = [[SomeObjectiveCClassImplementingOBJCSwiftProtocol alloc] init];
[anotherInstanceAsProtocol isKindOfClass:[SomeObjectiveCClassImplementingOBJCSwiftProtocol class]];
I get the warning "No known instance method for selector 'isKindOfClass:'"
If I modify the last line to
[(id)anotherInstanceAsProtocol isKindOfClass:[SomeObjectiveCClassImplementingOBJCSwiftProtocol class]]
It runs perfectly.
It also works if I assign to NSObject<SwiftProtocol> instead of id<SwiftProtocol>, but I think neither should be necessary.
Why is this cast necessary?

The problem is that your SwiftProtocol does not inherit from NSObject(Protocol) therefore the Obj-C compiler does not know that there is a method called isKindOfClass:.
Using id basically means you don't want any type checking at compilation time. The real fix should be to make the protocol extend NSObjectProtocol, making sure that all instances conforming to it are normal Obj-C objects.
Note that the history of Objective-C is complicated and not all Objective-C objects have to inherit from NSObject and have isKindOfClass: available.

Related

Objective-c syntax trouble [duplicate]

I'm a kind of self-programmer-made-man, so I'm missing some basic knowledge from time to time.
That's why I'm unable to really define well the topic of my question, because I don't know how to name it and how it works (but I know answer will seem trivial to many of you). When you know what's you're looking for it's a lot easier to find answers.
In objective-c, I can see lines of code like this :
aClassName *myObject = (aClassName *)[NSEntityDescription insertNewObjectForEntityForName:#"aClassName" inManagedObjectContext:app.managedObjectContext];
What's bother me is that (aClass *) part. What's this ?
I know/feel it's related to very basic knowledge but I can't name it so I can't find it.
My guess (and that's how I use it up to now) is that's used for calling class methods (+) but i'm not sure of it and it may be more deep that what I understand.
Thanks for any explanation.
It's a cast, in this case a down cast (even because up casts are implicit).
A cast is an operation that the developer does while writing the code to hint the compiler that a type is narrower than the one the compiler is thinking about.
Think about the following situation:
Class *a = [[Subclass alloc] init];
Subclass *b = a;
(assume that Subclass is a subclass of Class)
This won't compile because a is statically defined with a type which is not contained in Subclass. But the assignment wouldn't create any problem dynamically because a is used to store a Subclass object in practice.
So what you do? You place a cast Subclass *b = (Subclass*)a; to tell the compiler "trust me and ignore typechecking that assignment, I assert that it will be valid a runtime", and you automagically remove the compilation error. Forcing this behaviour of course removes type safety from your code, so you must know what you are doing.
Of course to understand the meaning of a cast in this situation you must at least know about inheritance and objects..
In your specific situation the return type of the method +(id)insertNewObjectForEntityForName:... is id, which is the least specific kind of object in ObjectiveC, it always needs to be casted to something if not stored just like a plain id
It is type cast:
double x = 5.0;
int y = (int)x;
I don't know why it is there in your case, as far as I know that method returns id, so the cast is not necessary (even without it no compiler warning will be generated).
Regarding “where to find such information”: Objective-C/C++ are built upon C and C++ correspondingly, so I'd recommend to learn basics of those languages first.
thats simply mean casting the object to type of the class inside the brackets for example here we cast the defention UITableViewCell to CustomCell
CustomeCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = (CustomeCell*)[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
... class methode is a different somthing its function that you can call without need to define an instance of the class ... when you call a instance method you need to do like this
Class *obj = [Class alloc] init];
[obj funtionName];
in Class ethod you just do like this
[Class funtionName];
hope this will be helpful.

How is type safety possible for an object pointer of id?

I have the following class (picked out of a Apple example):
#interface LeTemperatureAlarmService : NSObject <CBPeripheralDelegate>
#property (readonly) CBPeripheral *servicePeripheral;
#end
and in a different class's method I use the following code:
NSMutableArray *connectedServices = [[NSMutableArray alloc] init];
... // Adding some myService objects to connectedServices
for (id service in connectedServices) {
if ([service servicePeripheral] == parameter) {
...
}
}
Now the thing which drives me crazy is the part where I can send servicePeripheral to service.
As far as I understand how id works, it's basically a pointer which can be literally point to any object. My NSMutableArray is an untyped array which can hold any type of object in it, even mixed, so I don't have to be careful what I put in.
So how can it be that I can use [service servicePeripheral] even though I never specified the type of service? And how does Xcode know that and even suggest that method in code completion?
Objective-C works different in the respect of method invocation than say C++. The compiler doesn't have to know, because it's not done at compile time, methods are invoked at runtime. Specifically, methods are send to objects, instead of called on them. You send the servicePeripheral method to the object and the runtime takes care of calling the right function. This also makes it possible for you to send methods to nil without crashing (it will return false/0/NULL)
Types in Objective-C are mostly used for compile time safety, which you lose with your approach. The compiler can't warn you that the types don't match, for instance, your array can very well contain NSString instances or anything, and the compiler can't help you there since you tell it that you expect id (aka anything, really) and servicePeripheral is a perfectly valid and known method. You can add type safety by checking the class of the object at runtime using isKindOfClass:, for example like this:
for (id service in connectedServices) {
if ([service isKindOfClass:[LeTemperatureAlarmService class]] && [service servicePeripheral] == parameter) {
...
}
}
So how can it be that I can use [service servicePeripheral] even though I never specified the type of service?
It is exactly because you declared service as an id. This tells the compiler to turn off all static type-checking and permit you to send any message to service. That is what id is: it is the universal recipient (any message can be sent to it, any object value can be assigned to it) and the universal donor (it can be assigned to any object variable).
And you are perfectly right to be wary of this, since it can cause you to crash later. It is not (as your question title has it) "type safety". It is type unsafety! The compiler will happily let you say (for example) [service count] (because service is typed as an id), but you will crash later when the app runs, because this object does not respond to the count message.
So don't do that! Use explicit types so the compiler can help you in advance.

Would it be beneficial to begin using instancetype instead of id?

Clang adds a keyword instancetype that, as far as I can see, replaces id as a return type in -alloc and init.
Is there a benefit to using instancetype instead of id?
Yes, there are benefits to using instancetype in all cases where it applies. I'll explain in more detail, but let me start with this bold statement: Use instancetype whenever it's appropriate, which is whenever a class returns an instance of that same class.
In fact, here's what Apple now says on the subject:
In your code, replace occurrences of id as a return value with instancetype where appropriate. This is typically the case for init methods and class factory methods. Even though the compiler automatically converts methods that begin with “alloc,” “init,” or “new” and have a return type of id to return instancetype, it doesn’t convert other methods. Objective-C convention is to write instancetype explicitly for all methods.
Emphasis mine. Source: Adopting Modern Objective-C
With that out of the way, let's move on and explain why it's a good idea.
First, some definitions:
#interface Foo:NSObject
- (id)initWithBar:(NSInteger)bar; // initializer
+ (id)fooWithBar:(NSInteger)bar; // class factory
#end
For a class factory, you should always use instancetype. The compiler does not automatically convert id to instancetype. That id is a generic object. But if you make it an instancetype the compiler knows what type of object the method returns.
This is not an academic problem. For instance, [[NSFileHandle fileHandleWithStandardOutput] writeData:formattedData] will generate an error on Mac OS X (only) Multiple methods named 'writeData:' found with mismatched result, parameter type or attributes. The reason is that both NSFileHandle and NSURLHandle provide a writeData:. Since [NSFileHandle fileHandleWithStandardOutput] returns an id, the compiler is not certain what class writeData: is being called on.
You need to work around this, using either:
[(NSFileHandle *)[NSFileHandle fileHandleWithStandardOutput] writeData:formattedData];
or:
NSFileHandle *fileHandle = [NSFileHandle fileHandleWithStandardOutput];
[fileHandle writeData:formattedData];
Of course, the better solution is to declare fileHandleWithStandardOutput as returning an instancetype. Then the cast or assignment isn't necessary.
(Note that on iOS, this example won't produce an error as only NSFileHandle provides a writeData: there. Other examples exist, such as length, which returns a CGFloat from UILayoutSupport but a NSUInteger from NSString.)
Note: Since I wrote this, the macOS headers have been modified to return a NSFileHandle instead of an id.
For initializers, it's more complicated. When you type this:
- (id)initWithBar:(NSInteger)bar
…the compiler will pretend you typed this instead:
- (instancetype)initWithBar:(NSInteger)bar
This was necessary for ARC. This is described in Clang Language Extensions Related result types. This is why people will tell you it isn't necessary to use instancetype, though I contend you should. The rest of this answer deals with this.
There's three advantages:
Explicit. Your code is doing what it says, rather than something else.
Pattern. You're building good habits for times it does matter, which do exist.
Consistency. You've established some consistency to your code, which makes it more readable.
Explicit
It's true that there's no technical benefit to returning instancetype from an init. But this is because the compiler automatically converts the id to instancetype. You are relying on this quirk; while you're writing that the init returns an id, the compiler is interpreting it as if it returns an instancetype.
These are equivalent to the compiler:
- (id)initWithBar:(NSInteger)bar;
- (instancetype)initWithBar:(NSInteger)bar;
These are not equivalent to your eyes. At best, you will learn to ignore the difference and skim over it. This is not something you should learn to ignore.
Pattern
While there's no difference with init and other methods, there is a difference as soon as you define a class factory.
These two are not equivalent:
+ (id)fooWithBar:(NSInteger)bar;
+ (instancetype)fooWithBar:(NSInteger)bar;
You want the second form. If you are used to typing instancetype as the return type of a constructor, you'll get it right every time.
Consistency
Finally, imagine if you put it all together: you want an init function and also a class factory.
If you use id for init, you end up with code like this:
- (id)initWithBar:(NSInteger)bar;
+ (instancetype)fooWithBar:(NSInteger)bar;
But if you use instancetype, you get this:
- (instancetype)initWithBar:(NSInteger)bar;
+ (instancetype)fooWithBar:(NSInteger)bar;
It's more consistent and more readable. They return the same thing, and now that's obvious.
Conclusion
Unless you're intentionally writing code for old compilers, you should use instancetype when appropriate.
You should hesitate before writing a message that returns id. Ask yourself: Is this returning an instance of this class? If so, it's an instancetype.
There are certainly cases where you need to return id, but you'll probably use instancetype much more frequently.
There definitely is a benefit. When you use 'id', you get essentially no type checking at all. With instancetype, the compiler and IDE know what type of thing is being returned, and can check your code better and autocomplete better.
Only use it where it makes sense of course (i.e. a method that is returning an instance of that class); id is still useful.
Above answers are more than enough to explain this question. I would just like to add an example for the readers to understand it in terms of coding.
ClassA
#interface ClassA : NSObject
- (id)methodA;
- (instancetype)methodB;
#end
Class B
#interface ClassB : NSObject
- (id)methodX;
#end
TestViewController.m
#import "ClassA.h"
#import "ClassB.h"
- (void)viewDidLoad {
[[[[ClassA alloc] init] methodA] methodX]; //This will NOT generate a compiler warning or error because the return type for methodA is id. Eventually this will generate exception at runtime
[[[[ClassA alloc] init] methodB] methodX]; //This will generate a compiler error saying "No visible #interface ClassA declares selector methodX" because the methodB returns instanceType i.e. the type of the receiver
}
You also can get detail at The Designated Initializer
**
INSTANCETYPE
**
This keyword can only be used for return type, that it matches with return type of receiver. init method always declared to return instancetype.
Why not make the return type Party for party instance, for example?
That would cause a problem if the Party class was ever subclassed. The subclass would inherit all of the methods from Party, including initializer and its return type. If an instance of the subclass was sent this initializer message, that would be return? Not a pointer to a Party instance, but a pointer to an instance of subclass. You might think that is No problem, I will override the initializer in the subclass to change the return type. But in Objective-C, you cannot have two methods with the same selector and different return types (or arguments). By specifying that an initialization method return "an instance of the receiving object," you would never have to worry what happens in this situation.
**
ID
**
Before the instancetype has been introduced in Objective-C, initializers return id (eye-dee). This type is defined as "a pointer to any object". (id is a lot like void * in C.) As of this writing, XCode class templates still use id as the return type of initializers added in boilerplate code.
Unlike instancetype, id can be used as more than just a return type. You can declare variables or method parameters of type id when you are unsure what type of object the variable will end up pointing to.
You can use id when using fast enumeration to iterate over an array of multiple or unknow types of objects. Note that because id is undefined as "a pointer to any object," you do not include an * when declaring a variable or object parameter of this type.
The special type instancetype indicates that the return type from the init method will be the same class as the type of object it is initializing (that is, the receiver of the init message). This is an aid for the compiler so that it can check your program and flag potential
type mismatches—it determines the class of the returned object based on context; that is, if you’re sending the init message to a newly alloc’ed Fraction object, the compiler will infer that the value returned from that init method (whose return type has been declared as type instancetype) will be a Fraction object. In the past the return type from an initialization method was declared as type id. This new type makes more sense when you consider subclassing, as the inherited initialization methods cannot explicitly define the type of object they will return.
Initializing Objects, Stephen G. Kochan, Programming in Objective-C, 6th Edition

Why do I need to cast before a method of an item of a NSArray can be called?

I am fairly new to Objective-C. Currently porting my own library from C#/Java to objective C.
I now run into a very strange problem for me.
I have a NSArray with several Note objects. I want to transpose on of these notes:
//Note.h
- (Note *) transpose: (int) semitones;
//Main
NSArray *notes = [get it from somewhere];
Note *transposedNote = [[notes objectAtIndex:0]transpose:1]; //Doesn't compile
Note *transposedNote = [(Note*)[notes objectAtIndex:0]transpose:1]//Does compile
Is this happening because there is already a transpose method available in the general libraries?
I thought due to the dynamic nature of objective-C at runtime it would be checked which class objectAtIndex returns and then sends the message to it?
It is my understanding that there is no runtime type checking for the assignment operator in Objective C. Since an array can contain a mixture of types, there is no way for the system to know what objectAtIndex returns.
How about
Note *transposedNote = [notes objectAtIndex:0]; // first line
[transposedNote transpose:1]; // second line
? Notice in the reference that objectAtIndex: returns an id, you will see it is pretty obvious:
In the code above, because id can fit into any object, the first line doesn't need to cast it into Note. In the second line I'm just calling a method on a Note so the compiler is happy.
In your code you are calling methods on the returned id object, so the compiler doesn't understand what you are trying to do. Just assign it to a Note reference and it will be fine.
Yes, the error is because there's already a transpose: method in AppKit. And you're also right that it normally doesn't cause an error when you have two unrelated classes implementing methods with the same name. The reason you get an error is because the two methods either return incompatible types or take incompatible types as arguments. In your particular case, you're seeing both problems:
-[NSResponder transpose:] takes an id and returns void
-[Note transpose:] takes an int and returns an id
These are totally incompatible types, and the compiler does need to know the types involved even if it doesn't know what exact method is going to be called.
It does compile unless you have -Werror set to treat warnings as errors.
It might produce a warning if the compiler doesn't already know about the selector or if the selector is declared in more than one class. In the former case, it should be necessary only to import the interface containing the selector. In the latter case, you'll need to do the cast to suppress the error.

Initializer 'initWithRequest' reserved in the API?

Are the names of some initializer methods like 'initWithRequest' reserved in the API?
I have the following classes
#interface MTURLRequest : NSObject {
...
}
...
#end
and
#class MTURLRequest;
#protocol MTURLRequestHandlerDelegate;
#interface MTURLRequestHandler : NSObject {
...
}
-(id)initWithRequest:(MTURLRequest*)request_ delegate:(id<MTURLRequestHandlerDelegate>)delegate_;
#end
#protocol MTURLRequestHandlerDelegate<NSObject>
...
#end
I get a compile warning at the line where I invoke the initializer
-(void)enqueueRequest:(MTURLRequest*)request_ {
...
MTURLRequestHandler *handler = [[MTURLRequestHandler alloc] initWithRequest:request_ delegate:self];
...
}
warning: incompatible Objective-C types 'struct MTURLRequest *', expected 'struct NSURLRequest *' when passing argument 1 of 'initWithRequest:delegate:' from distinct Objective-C type
There is no NSURLRequest in the code. If I rename the initializer to initWithMTURLRequest everything compiles without warnings. Replacing the forward declaration of the class MTURLRequest with an import statement did not change anything. Clean all targets and rebuild as well. And there is surrely no NSURLRequest *request_ in scope.
There is no 'initWithRequest' initializer in NSObject. At least I can not find any.
Any clue why this happens?
Exact duplicate. See: Can't figure out 'warning: incompatible Objective-C types'
This comment indicates that you haven't grokked a fundamental design points of Objective-C:
OK, thanks. I just renamed the
initializer. Hell, who reviewed the
compiler and did not reject Apples
submission for distributing it? :-) I
understand it that way. There may not
exist two identical selectors within
an application, when the types of
their parameters are different.
The compiler is behaving exactly as designed. Objective-C is designed to be both very simple and very precise in the use of types. Type based dispatch -- as offered by C++ and Java -- is not at all simple, though type precise.
As a part of the simplicity, the (id) type is offered as a generic reference to an object of any class (including metaclasses, technically). Combining that with type safety and multiple declarations of the same method name -- the same selector -- with different arguments leads to ambiguity that the compiler is correctly identifying.
Separating the alloc and init
invocations could be a solution too.
MTURLRequestHandler *requestHandler =
[MTURLRequestHandler alloc];
[requestHandler
initWithRequest:request_
delegate:self]
That isn't quite correct. The -initWithRequest:delegate: method is free to return a different object. Thus, you would need to do:
MTURLRequestHandler *requestHandler = [MTURLRequestHandler alloc];
requestHandler = [requestHandler initWithRequest:....];
This is highly atypical. Casting the return value of +alloc is more typical, though avoiding the issue entirely is the recommended pattern.
Note that the above is also the reason why you should always assign the result of calling super's designated initializer to self.