What does it mean to share an implementation? - objective-c

As the title notes I'm looking to understand what does it mean to share an implementation. To be more specific, I want to know HOW it works. I get what the words mean but I'm not clear on the process of how it works.
Ex. "The fast-enumeration implementation is shared between the Objective-C runtime and the Foundation framework."
This is from Apple's Cocoa Fundamentals doc. I was reading and came across this line and am trying to understand the process.
Thanks

This basically covers a somewhat contradictional programming pattern (which, in my opinion, is wrong): the Objective-C language, the libobjc runtime library and the Foundation framework aren't strictly separated. For example, some fundamental message names, such as retain, release, etc. are hard-coded into the Objective-C runtime library (e. g., in order ARC to recognize these as special memory management-related messages), and this is the case with the fast enumeration as well.
The countByEnumeratingWithState:objects:count: selector is recognized by the compiler, and it is emitted when the for (object in collection) syntax is encountered. Then the collection object, of which the class implements this hard-wired message of the protocol NSFastEnumeration, updates count, objects, its return value, etc. according to how the runtime library and the ABI expects it.
For historical reasons, there's such a tight coupling between these three things (the language/the compiler, the runtime library and the Foundation framework) that this hard-coding approach is usable and realistic, but it's also a terrible violation of separation of the language and the library. I even dare to say that this is a quite dirty hack.

Related

Cocoa Programming in C?

I would like to start programming on Mac. Please:
I don't really like Objective-C and I somewhat know C, I read that Objective-C is a "dialect" of C - is it possible to program in C and use all the libraries and frameworks provided by Mac OS (this is Cocoa, right?)?
is it possible to draw GUI in XCode's GUI Builder and then fill the logic in plain C?
if I want to use, say, Scintilla - how do I "load" its text editing component into a window in GUI builder? And how do I access its text buffers? And events?
Just learn Objective-C. It isn't that hard; much, much, simpler than, say, C++. The object model is extremely similar to Java or SmallTalk.
The entire Cocoa stack of APIs are all in Objective-C, the documentation is all in Objective-C, many of the design patterns (KVO, KVC, delegation) are inherently Objective-C isms and all of the examples are Objective-C.
You are going to have to have a working knowledge of Objective-C to effectively program the system anyway. Any attempts to avoid Objective-C is just going to make your job harder, yield less maintainable code, and vastly reduce the # of folks in the community who can help.
Sure, by interacting with the runtime directly. It means you'll be doing a lot of objc_msgSend() et al. It's going to be horribly painful, you might as well just learn the Objective-C syntax and be done with it. (I explicitly note the syntax, because you will still need to learn the way objc does things in order to even use the C APIs).
The bit I can be least helpful on first: without having heard of it, according to its website Scintilla is for win32 and GTK+. As I believe that there's still no Cocoa native version of GTK+, there is no way to use a Scintilla component in a Cocoa program. OS X is not based on X11 (or Win32, for that matter).
Objective-C adds Smalltalk-style objects and dynamic dispatch to C. However, it is a strict superset, so C code is directly callable. The various GUI components rely on the dynamic, reflective nature of Objective-C so cannot directly call C code. However, the whole toolkit is built around the model-view-controller paradigm. It is quite feasible to design your view in Interface Builder, write a thin shim of a controller in Objective-C that does little more than call appropriate C functions and write your model entirely in C. C code can call Objective-C code, so you can wrap as many of the system objects as you want.
So this i pretty much a 'yes' to your second bullet point. Also relevant is that although Objective-C springs from C, Apple have made C++ fully callable (search for Objective-C++), so that's also an option.
Well worth looking into is Core Foundation. OS X originally supported two top-level programming environments — Cocoa and Carbon. Cocoa is Objective-C, Carbon is C with a bunch of legacy support libraries (and is now deprecated, with no 64 bit runtime to be supplied). To support both of these, much of the core system functionality is exposed through C interfaces at the lowest level, including all collections, strings and other relatively primitive objects. A bunch of other performance critical things like Core Text, Core Graphics, etc are also normally done via a straight C interface, even if you're otherwise completely enthusiastic about Objective-C.
There is a C-based API for UI programming on Mac OS X called Carbon. If you really cannot stand the sight of Objective-C I would start there. Many Cocoa classes and APIs have corresponding Carbon datatypes, etc. and vice versa but not all of them. Fair warning, Carbon is considered a "legacy" API, and it will likely continue to be marginalized as time goes on. Many Carbon APIs are not available for 64bit applications for example
Cocoa specifically is an Objective-C based API, using it from C would be awkward and difficult if possible at all. It would require some knowledge of Objective-C runtime APIs and possibly internals or otherwise writing a bunch of wrappers.

OOP vs procedural in run-time

I have very simple question I cant find answer anywhere on the internet.
So, my question is, in procedural programming, code is in code section, which goes into Read Only memory area. Variables are either on stack or heap.
But OOP says that object are created in memory. So, does it mean even functions are written into R/W memory area?
And, does Os have to have some inbuilt OOP programs support? For example if OS doesent allowed to read instruction outside Read only code section. Thanks.
Generally, both OOP and procedural programming are abstractions which exist only at the source-code level. Once a program is compiled into executable machine-code, these abstractions cease to exist. So whether or not a particular language is OOP or procedural has no bearing on what regions of memory it uses, or where instructions are placed during execution.
The OS itself usually doesn't know or care whether a particular executable was written in an OOP or procedural language. It only cares that the executable uses binary op-codes compatible with its native instruction set, and that the executable has an ABI (binary interface) that it understands.
This is a good question.
Whereas as object constitutes functions and data as being placed in the same spot theoretically, most implementations split it. The way you do it, is that code is split out and stored into the RO segment. An object in the RW area then have a way to refer back to that code in the RO area. The coupling of code and data is only used conceptually by the human programmer and the type checker to ensure that you do not violate the rules and principles.
A Java/C#-like language will usually be made such that each object has a tag identifying the type of the object. The object itself is simply a struct containing all the fields laid out in a prespecified order. This tag can then be used to look up which function in the RO-area to call. The function in the RO-area is altered to take an extra parameter, called this or self through which the contents of said object can be reached. When the method needs to refer to fields, it knows the pre-specified order, so it can do that correclty. Note that there are some tricks needed to solve inheritance, but this is the crux of the idea.
A Python/Ruby-like language will usually make an object be a hash-table where a method is a pointer to the code in the RO-area (provided that the language is compiled and not run through a bytecode interpreter). Function calls are made by looking up the hash-table contents and following the code pointer. Fields are also looked up in the same hash table.
With those basics down, most implementations make tricks to avoid the part where a pointer is followed to find the function to call. They try to figure out and narrow down the possible call to a single function. Then they can replace the lookup with a direct call to the right function, a much faster solution.
the tl;dr version: The language semantics views fields and methods as part of an object. The implementation split them into RO and RW segments. As such no OS support is needed.
OOP doesn't say this. I have no idea where you read it, if you add a quote that would help.
Objects are variables, so what you know about variables is correct for objects. In languages like C# (.net framework actually) objects can only be stored in heap, because they are so called reference types. In C++ they can live anywhere.
But OOP says that object are created in memory. So, does it mean even functions are written into R/W memory area?
From this i concluded that you think that functions are objects. That is true in far not every OOP language. It is from functional languages where functions are first class objects. Functions are in majority of cases immutable and are placed in read only sections.
Common OSes like Windows, Linux and MacOsx are unaware of objects. This is purely program concept. .net framework and java vm provide layer of abstraction. They are execution environments that have build in object support.

Objective-c and c++ on linux

I have some maybe stupid question. What is the difference between C++ and objectice-c. Is there IDE for objective-c for linux ?
I'm going to expand a bit on DaVinci's point 1.
First the similarities:
Objective-C and C++ were both originally based on C. Both languages support an object oriented model. That's where the similarities end.
Objective-C is a strict superset of C, C++ is not. Any C program is also an Objective-C program. This is not necessarily the case with C++.
The syntax of Objective-C's OO extensions is closer to the syntax of Smalltalk than that of C whereas the reverse is the case with C++.
The philosophies behind the OO models is completely different too. Objective-C's model is dynamic in the spirit of Smalltalk. C++'s model is more static. With Objective-C, you send messages to objects and the object decides at run time how it is going to respond to the message. With C++ the methods that an object responds to - even the virtual ones - are defined at compile time. This makes Objective-C's object model immensely more powerful than C++'s object model. For instance, you can add whole sets of new methods to existing classes without using inheritance. You can even replace method implementations on the fly.
This all comes at a cost of course. Sending messages to Objective-C objects is quite a bit slower than calling C++ virtual functions. However, I think the benefits are worth the cost and you can always drop back to C for performance critical sections of code.
NB there is also a language called Objective-C++ which is the Objective-C OO extensions built on top of C++ instead of C.
they are simply two quite different languages.
I think gnustep is the only objective-C environment/library, it also has a IDE: project center, however Objective-Cs home is primarily on Apple products.

Making best use of Objective-C dynamic features

I have been using Objective-C for a little while but being from a static type background (C#) I think I am using it in a very static way. Declaring objects as id feels alien to me and I can't see what the benefits are. Can anyone shine a light for me to get a better understanding of this?
Objective-C is kind of a hybrid language, in which you can be as dynamic and as static as you want. You can declare all the types of all the variables if you want, you can even declare delegate variables as NSObject<Protocol>* if you want. The id type works less as a real type and more like a hint to the compiler telling him "hey, I know what I'm doing, just trust me on this", making the compiler avoid any type checking on that particular variable.
The first obvious benefit of the Objective-C type system is that container types (NSArray, NSDictionary, NSSet) accept and return id types. This removes the need for templates and generics altogether (like in C++, Java and C#).
Even better, you can actually have containers with elements of any kind inside. As long as you know what goes inside, nobody will complain if you add two NSStrings, one NSNumber and an NSValue inside the same NSArray. You can do that in other languages, but you have to use the "Object" base class, or the void* type, and then you require to box and unbox (or cast up and down) variables in order to get the same behaviour. In Objective-C you just assign, which removes the noise generated by casting operators and boxing operations. Then you can ask "respondsToSelector:" or "class" to each object, in order to know the identity and the operations you can perform with them, at runtime. In Objective-C, reflection is a first class citizen.
Another benefit is the reduced compilation times; the compilation of an Objective-C program is in general much faster than its equivalent in C++, given that there aren't that many type checks performed, and much linking is done at runtime. The compiler trusts more the programmer.
Finally, Objective-C's dynamic type system makes possible to have a tool like Interface Builder. This is the main reason why Cocoa and Cocoa Touch has faster development times; the GUI can generate code with "id" types all over the place, and this is deserialized whenever the NIB is loaded in memory. The only language that comes close to Objective-C in terms of UI design experience is C# (and VB.NET, of course) but at the price of a much heavier application.
I personally prefer to work with a more static type checking, and I even turn on the "Treat Warnings as Errors" setting in the Objective-C compiler; I've written a blog post about it:
http://akosma.com/2009/07/16/objective-c-compiler-warnings/
This is particularly useful when you are working with developers who are new to the language. It makes the compiler whine more often than usual :)
Static type system pundits might disagree with all these points, arguing that static type checking allows for "intellisense" IDEs and better maintenance in general. I worked using .NET for years (2001 - 2006) and I must say that dynamic languages tend to produce less code, are easier to read, and in general, gives more freedom to work. The tradeoff (there's always a tradeoff) is that there is less information at compile time. But as I tend to say, compilers are a poor man's suite of tests. The best thing IMHO is to have a good suite of tests, and a good bunch of human testers torturing your code to find bugs, no matter what language you choose.
Objective-C's dynamism shines not just in the fact that every object is an id. Rather, it shines in the power of the Objective-C runtime and the ease to use it. A few examples of clever uses of runtime by Apple itself:
DO allows you to set up an proxy object for an Obj-C object in a separate app / separate machine. This is done by intercepting all the message sent to the proxy object, packing it up, sending it to the other app, and invoking it there.
KVO is implemented by dynamically replacing the setter method so that it automatically notifies the observers. (Well it's in fact subtler than that...)
CoreData accessors are generated at run time for each subclass of NSManagedObject, etc.
And, you can use the runtime from your code, too. I once used it for a good effect, mimicking CoreData and generating accessors at the run time, and having only their declaration in the header file. Thus you can get the merit of both the static typing (compile time error from the declaration in the header) and the dynamism (runtime generation of methods).
Mike Ash has written an excellent series of blog posts on how the runtime works and how to use it effectively. You just have to read it! DO, KVO, message forwarding and more. There are also many other interesting posts on the net, like fun with kvc and higher-order messaging 1, 2.
It’s actually rather rare that you would need to declare an object as type id, as you should generally know what type you are expecting. Sometimes you might use an id<Protocol> type, if you don’t know the actual type of an object but know that it should conform to a specific protocol.
Is there a particular scenario you are thinking of?
Passing instance as id is common when designing action's method; connecting a button to a method, the target looks like doSomething:(id) sender;.
In this case, it allows different kind of controls to use the same action's method, without prior knowledge of what these controls will be. In the action's method code, you can test for the class of the sender or simply use its tag property, to decide what to do.
-(void) doSomething:(id) sender {
// Get the sender's tag whatever it is
int tag = [sender tag];
switch(tag) {
case 1:
// ...
break;
case 2:
// ...
break;
}
}

Too much C-Style in Objective-C programs?

Hi I'm writing this question because I'm a newbie in ObjC and a lot of doubts came to my mind when trying to make my fist training app. The thing is that I have a strong background in C, I've been programming in Java for the last year and I've done some collage stuff with Smalltalk (I mencione this because those are my programming references and those are the languages I'm comparing ObjC with).
The first problem I've encountered is that I don't know where to draw a line between ObjC and C, for example when dealing with math operations, Should I use math.h or there is a more "object-way" like you can do in Smalltalk (aNumber raisedTo: 3) ? How does a person with no background at all in C learns ObjC?.
Another thing that I couldn't find was a collection's protocol (I've looked over the Foundation Framework documentation given by Apple). Because I want to implement an expresion tree class and I wanna know if there are methods that all collections should implement (like in Smalltalk or Java) or I gotta check by hand every collection and see if there is a cool method that my new collection should have.
I don't know if I'm being too stupid or I'm searching for features that the language/framework doesn't have. I want to program in ObjC with the ObjC style not thinking in C, Java or Smalltalk.
Sorry if the question was too long.
Absolutely use <math.h>. You don't way to pay message sending overhead for functions that run in 30 cycles. Even function call overhead seems pretty steep at that point.
More generally, use as much or as little of C-style as you want to. I've seen Objective-C that was nothing but a couple C modules glued together with objective C messages, and I've seen Objective-C that essentially zero lines of code without the square brackets. I've seen beautiful, effective code written both ways. Good code is good code, however you write it.
In general, you'll use C features for numerical calculations. You'll generally use objects for most other things. The reason for this is that objects are way heavier than a simple scalar — there's just no benefit to it. Why would you ever write [[NSNumber numberWithInteger:1] numberByAddingNumber:[NSNumber numberWithInteger:2]] when you can just write 1+2? It's not only painful to read, it's far slower and it doesn't gain you anything.
On the other hand, Cocoa has rich object libraries for strings, arrays, networking and many other areas, and using those is a big win.
Knowing what's there — and thus what the easiest way to do something is — is just a matter of learning. If you think something should be there and you can't find it, you can ask either here or on Apple's Cocoa-Dev mailing list.
As for a collection protocol — there really isn't one. The closest thing to it is the NSFastEnumeration protocol, which defines precisely one method: countByEnumeratingWithState:objects:count:. This lets you use the for (id someObject in someCollection) syntax to enumerate the objects in a collection. Otherwise, all the collections define their own independent interfaces.
The first problem I've encountered is that I don't know where to draw a line between ObjC and C.
My rule is to use C wherever it makes sense to you. Objective-C has the benefit of letting you choose when to be procedural and when to be object-oriented. Go with what fits best with the code you're writing.
Another thing that I couldn't find was a collection's protocol [...] I want to implement an expresion tree class and I wanna know if there are methods that all collections should implement (like in Java) or I gotta check by hand every collection and see if there is a method that my collection should have.
Unlike Java, Objective-C does not have a master protocol for collections like the java.util.Collection interface. Also, there aren't a proliferation of specific container implementations as in Java. However, that gives you the freedom to implement a collection in a way that makes sense for your code.
For building a tree-like structure, you might take a look at NSTreeNode to see if it might be useful to leverage. (It may be more than you're need or want, but might be worth a shot.)
As far as rolling your own collection, I've learned a lot while creating CHDataStructures.framework, and you're welcome to use whatever you like from that code, or just look at my attempts at creating Cocoa-like structures, designed to complement the Foundation collections and operate similarly. Good luck!
Try to use each language for what it's good at. IMHO, this would include Obj-C objects but C-like code implementing methods. So use math.h and concise C code to implement logic, but don't be shy about using Obj-C classes to organize your larger blocks of functionality into something that makes sense.
Also, try to interact with the frameworks using their style so you're not running upstream.
As has been mentioned, there’s no real protocol for abstract collection classes (aside from the NSFastEnumeration protocol which provides the for(id item in collection) syntax when implemented), but there are conventions to follow.
Apple’s Introduction to Coding Guidelines for Cocoa covers some of this, and there is in fact a section on naming collection methods which covers the general cases (though note that generic container classes such as NSArray use the term “Object” as opposed to “Element” listed in the examples there – i.e. addObject:, removeObject:, and so on).
Following the patterns listed here (among others) is actually crucial when you want your classes to be KVC-compliant, which allows other users to observe changes in your object’s properties.