Monomorphic arrays with static type checking - objective-c

id<UIView> views = #[one, two, three];
NSInteger object = [views lastObject]; // Compiler will warn me that `views` stores only UIViews
How far would I have to go implement this? Does anybody have some experience with extending clang to support similar features?
Similar: nsmutablearray-force-the-array-to-hold-specific-object-type-only

I have thought about this also, though in the end I ask would it actually make me more productive. Objective-C seems to me to be a very pragmatic language, the features it has are real world useful, things like block are super useful, but features like namespaces and typed arrays in my experience not so much. I add a lot of NSAssert to my code to check stuff like that. Usually my mutable collections are contained within other classes and so I have a lot of control over what can be added to them, but maybe thats a pattern I adopt because I don't have typed collections?

Well, technically you already can...
UIView *views[] = {one, two, three};
NSInteger object = views[2];
Or, more usefully, you could use Objective-C++.

Related

Objective-C: Checking class type, better to use isKindOfClass, or respondsToSelector?

Is it more appropriate to check a class's type by calling isKindOfClass:, or take the "duck typing" approach by just checking whether it supports the method you're looking for via respondsToSelector: ?
Here's the code I'm thinking of, written both ways:
for (id widget in self.widgets)
{
[self tryToRefresh:widget];
// Does this widget have sources? Refresh them, too.
if ([widget isKindOfClass:[WidgetWithSources class]])
{
for (Source* source in [widget sources])
{
[self tryToRefresh:source];
}
}
}
Alternatively:
for (id widget in self.widgets)
{
[self tryToRefresh:widget];
// Does this widget have sources? Refresh them, too.
if ([widget respondsToSelector:(#selector(sources))])
{
for (Source* source in [widget sources])
{
[self tryToRefresh:source];
}
}
}
It depends on the situation!
My rule of thumb would be, is this just for me, or am I passing it along to someone else?
In your example, respondsToSelector: is fine, since all you need to know is whether you can send the object that message, so you can do something with the result. The class isn't really that important.
On the other hand, if you were going to pass that object to some other piece of code, you don't necessarily know what messages it will be intending to send. In those cases, you would probably be casting the object in order to pass it along, which is probably a clue that you should check to see if it really isKindOfClass: before you cast it.
Another thing to consider is ambiguity; respondsToSelector: tells you an object will respond to a message, but it could generate a false positive if the object returns a different type than you expect. For example, an object that declares a method:
- (int)sources;
Would pass the respondsToSelector: test but then generate an exception when you try to use its return value in a for-in loop.
How likely is that to happen? It depends on your code, how large your project is, how many people are writing code against your API, etc.
It's slightly more idiomatic Objective C to use respondsToSelector:. Objective C is highly dynamic, so your design time assumptions about class structure may not necessarily hold water at run time. respondsToSelector: gets round that by giving you a shortcut to the most common reason for querying the type of a class - whether it performs some operation.
In general where there's ambiguity around a couple of equally appealing choices, go for readability. In this case that means thinking about intent. Do you care if it's specifically a WidgetWithSources, or do you really just care that it has a sources selector? If it's the latter, then use respondsToSelector:. If the former, and it may well be in some cases, then use isKindOfClass. Readability, in this case, means that you're not asking the reader to make the connection between type equivalence of WidgetWithSources and the need to call sources. respondsToSelector: makes that connection for the reader, letting them know what you actually intended. It's a small act of kindness towards your fellow programmer.
Edit: #benzado's answer is nicely congruent.
Good answers from #Tim & #benzado, here is a variation on the theme, the previously covered two cases first:
If at some point you have may have a reference to distinct classes and need them differently then this is probably a case for isKindOfClass: For example, an color might be stored in preferences as either an NSData serialization on an NSColor, or as an NSString value with one of the standard names; to obtain the NSColor value in this case isKindOfClass: on the object return is probably appropriate.
If you have a reference to a single class but different versions of it over time have supported different methods then consider respondsToSelector: For example, many framework classes add new methods in later versions of the OS and Apple's standard recommendation is to check for these methods using respondsToSelector: (and not an OS version check).
If you have a reference to distinct classes and you are testing if they adhere to some informal protocol then:
If this is code you control you can switch to a formal protocol and then use conformsToProtocol: as your test. This has the advantage of testing for type and not just name; otherwise
If this is code you do not control then use respondsToSelector:, but we aware that this is only testing that a method with the same name exists, not that it takes the same types of arguments.
Checking either might be a warning that you are about to make a hackish solution. The widget already knows his class and his selectors.
So a third option might be to consider refactoring. Moving this logic to a [widget tryToRefresh] may be cleaner and allow future widgets to implement additional behind the scenes logic.

What's the most efficient way to make immutable and mutable versions of an objective-c class?

Suppose I’m making an Objective-C class that represents a fraction, and want to create immutable and mutable versions.
Following the patterns in the Foundation framework, you might expect to see the method fractionByAddingFraction: in the immutable version and addFraction: in the mutable version.
The paradox I’m running into is how to only include the fraction-adding logic once between the two classes. It seems that the immutable fractionByAddingFraction: method needs to know about (and make use of) the mutable addFraction: method in order to avoid code duplication, and yet including the mutable methods in the implementation of the immutable class means they could conceivably be called on the immutable object, which defeats the point.
A brief explanation (or better still, a continuation of this simplified example) would be much appreciated!
Your approach is correct (if you really need a mutable subclass, which you should avoid unless you actually need it). I'm not quite clear where the confusion is coming in. You would most easily implement addFraction: using fractionByAddingFraction:. It would be a little inefficient, but that's the direction that would make the most sense. Something like:
- (void)addFraction:(Fraction *)anotherFraction {
Fraction *newFraction = [self fractionByAddingFraction:anotherFraction];
self.internalStuff = newFraction.internalStuff;
}
But typically you would probably handle this more efficiently with some private _GetInternalStuffByAddingInternalStuffs() function that both classes would use.
The primary implementations of Foundation’s collections cheat: there’s only one implementation, which is a subclass of NSMutableFoo, and it has a private mutability flag. This means client code can’t test whether a particular object is mutable or not, but that would never be a good idea anyway except perhaps for debugging and assertions.

iPhone, is using isKindOfClass considered bad practice in any way?

For example if there is a 'handle all' type method...
if ([obj isKindOfClass:class1]) {
// ...
} else if ([obj isKindOfClass:class2]) {
// etc..
Is this bad practice? Is there a neater alternative or a better way to structure the code?
Are there disadvantages in tearms of runtime, readability, maintainability or anything?
Whenever something is considered good/bad practice, it is more or less subjective. When doing something is inherently right/wrong, it is more or less objective.
isKindOfClass: is a useful method to check class inheritance. It answers the only question, "is the object of a class which is (a subclass of) a given class?". It doesn't answer any other questions like "does this object implement that method in its own way?" or "can I use the object for X or Y?". If you use isKindOfClass: as intended, you won't have any problems. After all, in a dynamic typed language you ought to have tools to extract meta information about objects. isKindOfClass: is just one of the available tools.
The fact that certain objects may lie about their class should not really put you off. They just disguise themselves as objects of another class without breaking anything. And if that doesn't break anything, why should I care?
The main thing is that you should always remember to use the right tool for any given purpose. For example, isKindOfClass: is no substitute for respondsToSelector: or conformsToProtocol:.
Sort of. This question basically covers what you're asking: Is it safe to use isKindOfClass: against an NSString instance to determine type?
There are some caveats you need to bear in mind (see link above), but personally I think it's a fairly readable method. You just need to make sure what you're doing inside your conditional test is appropriate (the example Apple give is along the lines of "an object may say it's a kind of NSMutableArray, but you might not be able to mutate it").
I would consider the example you gave to be an anti-pattern, so yes, I would say it is harmful. Using isKindOf like that is defeating polymorphism and object orientation.
I would far prefer that you call:
[obj doTheThing];
and then implement doTheThing differently in your subclasses.
If obj could belong to classes that you don't have control over, use categories to add your doTheThing method to them. If you need default behaviour, add a category on NSObject.
This is a cleaner solution in my opinion, and it helps to separate the logic (what you're doing) from the implementation details (how to do it for specific different types of object).

cannot convert 'b2PolygonShape' to 'objc_object*' in argument passing

I am not sure if many of you are familiar with the box2d physics engine, but I am using it within cocos2d and objective c.
This more or less could be a general objective-c question though, I am performing this:
NSMutableArray *allShapes = [[NSMutableArray array] retain];
b2PolygonShape shape;
..
..
[allShapes addObject:shape];
and receiving this error on the addObject definition on build:
cannot convert 'b2PolygonShape' to 'objc_object*' in argument passing
So more or less I guess I want to know how to add a b2PolygonShape to a mutable array. b2PolygonShape appears to just be a class, not a struct or anything like that. The closest thing I could find on google to which I think could do this is described as 'encapsulating the b2PolygonShape as an NSObject and then add that to the array', but not sure the best way to do this, however I would have thought this object should add using addObject, as some of my other instantiated class objects add to arrays fine.
Is this all because b2PolygonShape does not inherit NSObject at it's root?
Thanks
b2PolygonShape is a C++ class, not an ObjC class. You can only put ObjC instances into "NS-containers".
Since you need C++ anyway, it's better to use a std::vector<b2PolygonShape>.
NS-container classes can (as KennyTM pointed out) only store NSObjects. This can be a bit of a pain sometimes. But there are plenty of alternatives to NS-containers.
You can write Objective-C wrapper classes (or use NSValue), and store these in an NSArray.
You could use a plain old C array (though, that may not serve your needs, if the array size is undefined and shrinks and grows)
You could use a hash table to store your references.
A linked list of structs can also come in handy, and is fairly easy to create and maintain.
Should you decide to stick to std::vector, which is as good a solution as any, you can read more about that at: http://www.cplusplus.com/reference/stl/vector/

Dot notation vs. message notation for declared properties [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 months ago.
Improve this question
We now have the "dot" notation for properties. I've seen various back and forths about the merits of dot notation vs. message notation. To keep the responses untainted I'm not going to respond either way in the question.
What is your thought about dot notation vs. message notation for property accessing?
Please try to keep it focused on Objective-C - my one bias I'll put forth is that Objective-C is Objective-C, so your preference that it be like Java or JavaScript aren't valid.
Valid commentary is to do with technical issues (operation ordering, cast precedence, performance, etc), clarity (structure vs. object nature, both pro and con!), succinctness, etc.
Note, I'm of the school of rigorous quality and readability in code having worked on huge projects where code convention and quality is paramount (the write once read a thousand times paradigm).
Do not use dot for behavior. Use dot to access or set attribute like stuff, typically attributes declared as properties.
x = foo.name; // good
foo.age = 42; // good
y = x.retain; // bad
k.release; // compiler should warn, but some don't. Oops.
v.lockFocusIfCanDraw; /// ooh... no. bad bad bad
For folks new to Objective-C, I would recommend not using the dot for anything but stuff declared as #property. Once you have a feel for the language, do what feels right.
For example, I find the following perfectly natural:
k = anArray.count;
for (NSView *v in myView.subviews) { ... };
You can expect that the clang static analyzer will grow the ability to allow you to check that the dot is being used only for certain patterns or not for certain other patterns.
Let me start off by saying that I started programming in Visual/Real Basic, then moved on to Java, so I'm fairly used to dot syntax. However, when I finally moved to Objective-C and got used to brackets, then saw the introduction of Objective-C 2.0 and its dot syntax, I realized that I really don't like it. (for other languages it's fine, because that's how they roll).
I have three main beefs with dot syntax in Objective-C:
Beef #1: It makes it unclear why you might be getting errors. For example, if I have the line:
something.frame.origin.x = 42;
Then I'll get a compiler error, because something is an object, and you can't use structs of an object as the lvalue of an expression. However, if I have:
something.frame.origin.x = 42;
Then this compiles just fine, because something is a struct itself that has an NSRect member, and I can use it as an lvalue.
If I were adopting this code, I would need to spend some time trying to figure out what something is. Is it a struct? Is it an object? However, when we use the bracket syntax, it's much clearer:
[something setFrame:newFrame];
In this case, there is absolutely no ambiguity if something is an object or not. The introduction of ambiguity is my beef #1.
Beef #2: In C, dot syntax is used to access members of structs, not call methods. Programmers can override the setFoo: and foo methods of an objects, yet still access them via something.foo. In my mind, when I see expressions using dot syntax, I'm expecting them to be a simple assignation into an ivar. This is not always the case. Consider a controller object that mediates an array and a tableview. If I call myController.contentArray = newArray;, I would expect it to be replacing the old array with the new array. However, the original programmer might have overridden setContentArray: to not only set the array, but also reload the tableview. From the line, there's no indication of that behavior. If I were to see [myController setContentArray:newArray];, then I would think "Aha, a method. I need to go see the definition of this method just to make sure I know what it's doing."
So I think my summary of Beef #2 is that you can override the meaning of dot syntax with custom code.
Beef #3: I think it looks bad. As an Objective-C programmer, I'm totally used to bracket syntax, so to be reading along and see lines and lines of beautiful brackets and then to be suddenly broken with foo.name = newName; foo.size = newSize; etc is a bit distracting to me. I realize that some things require dot syntax (C structs), but that's the only time I use them.
Of course, if you're writing code for yourself, then use whatever you're comfortable with. But if you're writing code that you're planning on open sourcing, or you're writing something you don't expect to maintain forever, then I would strong encourage using bracket syntax. This is, of course, just my opinion.
Blog post against dot syntax: https://bignerdranch.com/blog/dot-notation-syntax/
Rebuttal to above post: http://eschatologist.net/blog/?p=226 (with original article in favor of dot syntax: http://eschatologist.net/blog/?p=160)
I'm a new Cocoa/Objective-C developer, and my take on it is this:
I stick to the messaging notation, even though I started with Obj-C 2.0, and even though the dot notation is more familiar feeling (Java is my first language.) My reason for this is pretty simple: I still don't understand exactly why they added the dot notation to the language. To me it seems like an unnecessary, "impure" addition. Although if anyone can explain how it benefits the language, I'd be happy to hear it.
However, I consider this a stylistic choice, and I don't think there is a right or wrong way, as long as it's consistent and readable, just as with any other stylistic choice (like putting your opening curly brace on the same line as the method header or the next line).
Objective-C dot notation is a syntactic sugar that is translated to normal message passing, so under the hood changes nothing and makes no difference at runtime. Dot notation it is absolutely not faster than message passing.
After this needed little preamble here's pros and cons seen by me :
Dot notation pros and cons
pros
readability : dot notation is easier to read than nested brackets massages passing
It simplifies interaction with Attributes and Properties: using dot notation for properties and message notation for methods you can achieve separation of state and behavior at the synthax level
It is possible to use compound assignment operator (1).
using the #property and dot notation the compiler do a lot of work for you, it can generate code for good Memory Management when getting and setting the property; this is why dot notation is suggested by Apple itself official guides.
cons
Dot notation is allowed only for access to a declared #property
Since Objective-C is a layer above standard C(language extension), the dot notation doesn’t really make clear if the accessed entity is a an object or a struct. Often, it looks like you are accessing properties of a struct.
calling a method with the dot notation you lose named parameters readability advantages
when mixed message notation and dot notation seems like you are coding in two different languages
Code Examples :
(1)Compound operator usage code example :
//Use of compound operator on a property of an object
anObject.var += 1;
//This is not possible with standard message notation
[anObject setVar:[anObject var] + 1];
Using the style of a language, consistent with the language itself, is the best advice here. However, this isn't a case of writing functional code in an OO system (or vice versa) and the dot notation is part of the syntax in Objective-C 2.0.
Any system can be misused. The existence of the preprocessor in all C based languages is enough to do really quite weird things; just look at the Obfuscated C Contest if you need to see exactly how weird it can get. Does that mean the preprocessor is automatically bad and that you should never use it?
Using the dot syntax for accessing properties, which have been defined as such in the interface, is open to abuse. The existence of abuse in potentia shouldn't necessarily be the argument against it.
Property access may have side-effects. This is orthogonal to the syntax used to acquire that property. CoreData, delegation, dynamic properties (first+last=full) will all necessarily do some work under the covers. But that would be confusing 'instance variables' with 'properties' of an object. There's no reason why properties should necessarily need to be stored as-is, especially if they can be computed (e.g. length of a String, for example). So whether you use foo.fullName or [foo fullName] there's still going to be dynamic evaluation.
Lastly, the behaviour of the property (when used as an lvalue) is defined by the object itself, like whether a copy is taken or whether it is retained. This makes it easier to change the behaviour later - in the property definition itself - rather than having to re-implement methods. That adds to the flexibility of the approach, with the resulting likelihood of less (implementation) errors occurring. There's still the possibility of choosing the wrong method (i.e. copy instead of retain) but that's an architectural rather than implementation issue.
Ultimately, it boils down to the 'does it look like a struct' question. This is probably the main differentiator in the debates so far; if you have a struct, it works differently than if you have an object. But that's always been true; you can't send a struct a message, and you need to know if it's stack-based or reference/malloc based. There are already mental models which differ in terms of usage ([[CGRect alloc] init] or struct CGRect?). They've never been unified in terms of behaviour; you need to know what you're dealing with in each case. Adding property denotation for objects is very unlikely to confuse any programmer who knows what their data types are; and if they don't, they've got bigger problems.
As for consistency; (Objective-)C is inconsistent within itself. = is used both for assignment and equality, based on lexical position in the source code. * is used for pointers and multiplication. BOOLs are chars, not bytes (or other integer value), despite YES and NO being 1 and 0 respectively. Consistency or purity isn't what the language was designed for; it was about getting things done.
So if you don't want to use it, don't use it. Get it done a different way. If you want to use it, and you understand it, it's fine if you use it. Other languages deal with the concepts of generic data structures (maps/structs) and object types (with properties), often using the same syntax for both despite the fact that one is merely a data structure and the other is a rich object. Programmers in Objective-C should have an equivalent ability to be able to deal with all styles of programming, even if it's not your preferred one.
I've mostly been raised in the Objective-C 2.0 age, and I prefer the dot notation. To me, it allows the simplification of code, instead of having extra brackets, I can just use a dot.
I also like the dot syntax because it makes me really feel like I'm accessing a property of the object, instead of just sending it a message (of course the dot-syntax really does translate into message sending, but for the sake of appearances, the dot feels different). Instead of "calling a getter" by the old syntax, it really feels like I'm directly getting something useful from the object.
Some of the debate around this is concerned with "But we already have dot-syntax, and it's for structs!". And that's true. But (and again, this is just psychological) it basically feels the same to me. Accessing a property of an object using dot-syntax feels the same as accessing a member of a struct, which is more or less the intended effect (in my opinion).
****Edit: As bbum pointed out, you can also use dot-syntax for calling any method on an object (I was unaware of this). So I will say my opinion on dot-syntax is only for dealing with properties of an object, not everyday message sending**
I use it for properties because
for ( Person *person in group.people){ ... }
is a little easier to read than
for ( Person *person in [group people]){ ... }
in the second case readability is interupted by putting your brain into message sending mode, whereas in the first case it is clear you are accessing the people property of the group object.
I will also use it when modifying a collection, for instance:
[group.people addObject:another_person];
is a bit more readable than
[[group people] addObject:another_person];
The emphasis in this case should be in the action of adding an object to the array instead of chaining two messages.
I much prefer the messaging syntax... but just because that is what I learned. Considering a lot of my classes and what not are in Objective-C 1.0 style, I wouldn't want to mix them. I have no real reason besides "what I'm used to" for not using the dot syntax... EXCEPT for this, this drives me INSANE
[myInstance.methodThatReturnsAnObject sendAMessageToIt]
I don't know why, but it really infuriates me, for no good reason. I just think that doing
[[myInstance methodThatReturnsAnObject] sendAMessageToIt]
is more readable. But to each his own!
Honestly, I think it comes down to a matter of style. I personally am against the dot syntax (especially after just finding out that you can use it for method calls and not just reading/writing variables). However, if you are going to use it, I would strong recommend not using it for anything other than accessing and changing variables.
One of the main advantages of object-oriented programming is that there is no direct access to internal state of the objects.
Dot syntax seems to me to be an attempt to make it look and feel as though state is being accessed directly. But in truth, it's just syntactic sugar over the behaviors -foo and -setFoo:. Myself, I prefer to call a spade a spade. Dot syntax helps readability to the extent that code is more succinct, but it doesn't help comprehension because failing to keep in mind that you're really calling -foo and -setFoo: could spell trouble.
Synthesized accessors seem to me to be an attempt to make it easy to write objects in which state is accessed directly. My belief is that this encourages exactly the kind of program design that object-oriented programming was created to avoid.
On balance, I would rather dot syntax and properties had never been introduced. I used to be able to tell people that ObjC is a few clean extensions to C to make it more like Smalltalk, and I don't think that's true any more.
In my opinion, the dot syntax makes Objective-C less Smalltalk-esque. It can make code look simpler, but adds ambiguity. Is it a struct, union, or object?
Many people seems to be mixing up 'properties' with 'instance variables'.
The point of the properties is to make it possible to modify the object without having to know its internals, I think. The instance variable is, most of the time, the 'implementation' of a property (which in turn is the 'interface'), but not always: sometimes a property does not correspond to an ivar, and instead it calculates a return value 'on the fly'.
That's why I believe the idea that "the dot syntax tricks you into thinking you're accessing the variable so it's confusing" is wrong. Dot or bracket, you shouldn't make assumptions about the internals: it's a Property, not an ivar.
I think I might switch to messaging instead of dot notation because in my head object.instanceVar is just instanceVar that belongs to object, to me it doesn't look at all like a method call, which it is, so there could be things going on in your accessor and whether you use instanceVar or self.instanceVar could have much more of a difference than simply implicit vs. explicit. Just my 2¢.
The dot notation tries to make messages look like accesses to a member of a struct, which they are not. Might work fine in some cases. But soon someone will come up with something like this:
NSView *myView = ...;
myView.frame.size.width = newWidth;
Looks fine. But is not. It's the same as
[myView frame].size.width = newWidth;
which doesn’t work. The compiler accepts the first, but rightfully not the second. And even if it emitted an error or warning for the first this is just confusing.
Call me lazy but if I had to type a single '.' vs. two [ ] each time to get the same results I would prefer a single . I hate verbose languages. The () in lisp drove me nuts. Elegant language such as mathematics are concise and effective, all others fall short.
Use dot notation (whenever you can)
On instance methods returning some value
Do not use dot notation
On instance methods returning void, on init methods or on Class method.
And my personal favorite exception
NSMutableArray * array = #[].mutableCopy;
I personally don't use dot-notation at all in code. I only use it in CoreData KVC binding expression when required.
The reason for not using them in code for me is that the dot-notation hides the setter semantics. Setting a property in dot-notation always looks like assignment regardless of the setter semantics (assign/retain/copy). Using the message-notation makes it visible that the receiving object has control over what happens in the setter and underlines the fact the those effects need to be considered.
I'm still considering whether I might want to use dot-notation when retrieving the value of a KVC compliant or declared property because it admittedly is a bit more compact and readable and there are no hidden semantics. Right now I'm sticking with message-notation for sake of consistency.
OK, dot notation in Objective-C looks strange, indeed. But I still can't do the following without it:
int width = self.frame.size.width;
Works fine, but:
int height = [[[self frame] size] height];
Gives me "Cannot convert to a pointer type". I'd really like to keep my code looking consistent with message notation, though.
This is a great question and I see many different answers to this. Although many have touched upon the topics, I will try to answer this from a different angle (some might have done it implicitly):
If we use the 'dot' notation, the resolution of the target for the method is done at compile time. If we use message passing, the resolution of the target is deferred to run-time execution. If the targets are resolved at compile time, the execution is faster, since resolving the targets at the run-time includes a few overheads. (Not that the time difference will matter much). Since we have defined the property in the interface of the object already, there is no point in differing the resolution of the target for a property to run-time and hence dot-notation is the notation that we should use for accessing property.