Calling functions in C-like syntax [closed] - objective-c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How can I write code in Xcode max similar to syntax in Java or C++ in particular call functions (messages), static or dynamic? I just want to simply call Objective-C function in C-like syntax.
How to when I write NSString * s = NSString.alloc().init();
(or similar, for example, NSString::alloc().init(), or NSString::alloc.init or (new NSString()).alloc().init() ;))
in Xcode (or another iPhone dev environment), the compiler did not cause an error and it will run.
or code like
NSString * a = NSString.alloc().init(); //or similar
bool b = a.compare("abcdef"); //or bool b = a->compare("abcdef");
will run.
?

Objective-C has C functions. In fact, all valid C code is valid Objective-C code. So yes, you can call functions with C syntax.
However, objects and message sends use Objective-C's syntactic extensions to C, which are not configurable. They are part of the language. You can't change Objective-C's syntax any more than you could make C++ use Smalltalk syntax.

No, there is no way to call Objective-C methods in a different syntax, with one exception:
You can call methods that do not take arguments with a dot notation as in object.method (this is mostly used with properties, which in turn are getter and setter methods that are generated by the compiler).
So the way methods are called in Objective-C ([object method] or [object methodWithArgumentA:someValue argumentB:otherValue]) cannot be changed. This is the syntax chosen by the language designers. And once you've worked with it a little, you'll understand why:
Method names in Objective-C tend to be very descriptive and are used as if Objective-C had named arguments (technically, that's not the case). Like:
[someData writeToFile:aFileName atomically:YES];
How would you transfer this to a dot notation? It might look like this:
someData.writeToFileAtomically(aFileName, YES);
Now, if I see a method just writeToFileAtomically I wouldn't be surprised if it just would take one argument (whether to atomically write to file; but which file?) or no argument (just write to a file atomically; again, which file?). With the Objective-C notation the intention is more clear.
And now consider object.addObserverForKeyPathOptionsContext(o, k, op, c) vs. [object addObserver:o forKeypath:k options:op context:c].
Whether one likes this syntax or not is subjective. You don't seem to like it, as you wouldn't have asked how to get rid of it. But if you want to write Objective-C code you'll have to accept that this is the way it's done and you cannot change it. Embrace it, I found it weird at first as well (also coming from a long C++ and Java background) but now I miss the very verbose way of calling methods with arguments of Objective-C when working in other languages.

Related

Objective C not throwing enough errors? [closed]

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

What is the difference between [myString length] and myString.length in objective-c? [duplicate]

This question already has answers here:
Performance difference between dot notation versus method call in Objective-C
(5 answers)
Closed 8 years ago.
I'm currently learning objective-c. What exactly do the square braces around things signify and is there any difference between using that and using a period (I'm from a .NET world so this would be simpler for me).
Thanks.
They both do the same thing in your example. The . is a sort of shorthand used to access a property of an object. [] are used to send a message to the object. In your example, those happen to be the same thing. You'll notice the difference if you try to send a message that doesn't directly map to a property name.
For example: [myString length] and myString.length are the same, but if you wanted to set the length (let's assume that makes sense for the example's sake), you'd need to do something like [myString setLength:newLength] or myString.length = newLength. Besides that, there are messages that aren't the same as property names - like this example:
[myString stringByReplacingOccurrencesOfString:#"hello" withString:#"world"];
which has no meaningful equivalent using the . shorthand.
Objective-C uses messages, rather than methods, and that's the main syntax (the dot syntax was introduced as an alternative for simple get/set messages). There are obviously significant similarities between methods and messages, but also differences.
In Objective-C, objects have complete flexibility in responding to a message at runtime. They can handle a totally unexpected message, for instance by proxying it to another object. Or, you could do things like map messages to columns at runtime. This is based on a legacy going back to Smalltalk.
.NET only just got this flexibility with dynamic/DynamicObject/IDynamicMetaObjectProvider. Of course, in either language, method/message names defined at compile-time are usually more appropriate. But there are notable use cases for dynamic ones.
Of course, Objective-C is a superset of C, so the . is used for other things (generally structs or unions).

Suppressing Class Method Not Found Warnings in Xcode [duplicate]

This question already has answers here:
Using #pragma to suppress “Instance method not found” warnings in Xcode
(5 answers)
Closed 9 years ago.
I have a class whose methods are determined at runtime, as indicated in my question here. This works great, but now I have a bunch of warnings that look like the following littering my code:
Class method '+objectIsNotNil:' not found (return type defaults to 'id')
While these warnings don't actually affect the build process, they're very annoying and make it harder to spot relevant warnings. Is there some way to disable them, but only for the Assert class (maybe some kind of macro)? If this isn't possible, then is there some way to turn them off for the entire build?
One alternative would be to use performSelector:withObject: instead of the direct method call.
So instead of:
[Assert objectIsNotNil:object];
You could have:
[Assert performSelector:#selector(objectIsNotNil:) withObject:object];
It does not look quite as nice but it will remove the warnings. Furthermore, this pattern will work for any selector you want. To make things look a little better you could use macros in the following way:
#define ASSERT_PRECONDITION(sel, obj) [Assert performSelector:#selector(sel) withObject:obj]
This way your assert would look like this:
ASSERT_PRECONDITION(objectIsNotNil:, object);
these cases should be extremely rare...
I've declared a hidden protocol which declared the methods with proper signatures. 'Hidden' in the sense that it was only included by the translations which needed them.
#protocol MONRuntimeClassInterface
+ (BOOL)objectIsNotNil:(id)object;
#end
Easy answer:
You don't want to do this. And if I understand your problem right, you don't need to. You're defining all the relevant methods in your Predicate class described in the link and Assertion is just forwarding to them. Including Predicate.h and making sure everything's declared in the interface should work fine. Like methods called on objects typed id, the compiler will consider methods called on a Class object to be found so long as it knows of at least one class in that compilation unit that implements a class method with the same name.
Alternative answer:
If you really want to suppress compiler warnings, for example if you're calling a method that don't exist anywhere at compile-time then you need to use either NSObject's performSelector: method or the runtime function objc_msgSend(). This won't be checked for a matching method at compile time. However, for some C types which you could plausibly want to pass as arguments (floats and certain larger structs), the compiler needs to know their type. In the absence of a method definition, it needs information from you. performSelector: works by only accepting objects of type id. objc_msgSend needs casting casted to a function with the appropriate signature before it's called (and in some cases, replacing with a variant function). Mike Ash has a good explanation of how this works here.

Do "dynamic ivars" break the "strict superset of C" paradigm for Objective-c?

Thank you to Yuji for answering another question I had and pointing me to this article about dynamic ivars in Objective-C.
However, as explained in my other question the sizeof operator now behaves inconsistently. In short, sizeof will not take into account dynamic ivars from outside the class .m file but will take them into account inside the .m file after the #synthesize declarations that create the dynamic ivars.
So my question is does this break the idea that Objective-C is a strict superset of C?
No. All valid C code remains valid Objective-C code with the same meaning it has in C, so Objective-C is still a strict superset. Keep in mind that a superset is allowed to have features not found in a subset — that's the whole reason Objective-C can have all the additional capabilities and syntax that it does while remaining 100% C-compatible.
What this does affect is the implementation detail that Objective-C classes are essentially C struct types with a set of functions that act on them. Note that similar functionality to objC_setAssociatedObject() could be implemented for a CoreFoundation-style pure C struct without changing the C language itself at all — and it would have the similar side effect of making sizeof() not give a fully "accurate" idea of all the data the struct encompasses.
No. If you run Objective-C code through a C compiler it never would have compiled anyway. If you run C code through an Objective-C compiler it will behave exactly as if you had run it through a C compiler (barring compiler bugs).
If you ever find yourself writing sizeof(MyObjectiveCClass) you are almost certainly doing something horribly wrong that will be completely broken.

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.