Project without garbage collector osx - objective-c

in my school we recieved task to do project in any programming language, but with custom data structure and programming language can not have garbage collector. It was recommended to use C ++. But I have better skills in objective-c. So I disable ARC in my Xcode project and now I should create custom data structure like ArrayList in Java. I cant use NSMutableArray or NSArray. It is possible working with memory like in C++ and create custom data structure?
Thank you for response

You have two basic choices:
Use struct's for your data structures and malloc/free (and friends) for your dynamic memory allocation - just as you might in C(++); or
You can use NSObject derived classes and alloc/init/new/retain/release (and friends) for your dynamic memory management. To do this you must disable ARC.
Given this is a school task you might wish to check the second is acceptable - you are still using the Objective-C reference-counting machinery, even though you are calling the operations manually. Your professor may not deem that acceptable.
The first choice is more basic, you will be completely responsible for all decisions on when memory is no longer required. Indeed you may choose to implement your own reference counting or even mark-sweep.
HTH

Related

extending objects at run-time via categories?

Objective-C’s objects are pretty flexible when compared to similar languages like C++ and can be extended at runtime via Categories or through runtime functions.
Any idea what this sentence means? I am relatively new to Objective-C
While technically true, it may be confusing to the reader to call category extension "at runtime." As Justin Meiners explains, categories allow you to add additional methods to an existing class without requiring access to the existing class's source code. The use of categories is fairly common in Objective-C, though there are some dangers. If two different categories add the same method to the same class, then the behavior is undefined. Since you cannot know whether some other part of the system (perhaps even a system library) adds a category method, you typically must add a prefix to prevent collisions (for example rather than swappedString, a better name would likely be something like rnc_swappedString if this were part of RNCryptor for instance.)
As I said, it is technically true that categories are added at runtime, but from the programmer's point of view, categories are written as though just part of the class, so most people think of them as being a compile-time choice. It is very rare to decide at runtime whether to add a category method or not.
As a beginner, you should be aware of categories, but slow to create new ones. Creating categories is a somewhat intermediate-level skill. It's not something to avoid, but not something you'll use every day. It's very easy to overuse them. See Justin's link for more information.
On the other hand, "runtime functions" really do add new functionality to existing classes or even specific objects at runtime, and are completely under the control of code. You can, at runtime, modify a class such that it responds to a method it didn't previously respond to. You can even generate entirely new classes at runtime that did not exist when the program was compiled, and you can change the class of existing objects. (This is exactly how Key-Value Observation is implemented.)
Modifying classes and objects using the runtime is an advanced skill. You should not even consider using these techniques in production code until you have significant experience. And when you have that experience, it will tell you that you very seldom what to do this anyway. You will know the runtime functions because they are C-based, with names like method_exchangeImplmentations. You won't mistake them for normal ObjC (and you generally have to import objc/runtime.h to get to them.)
There is a middle-ground that bleeds into runtime manipulation called message forwarding and dynamic message resolution. This is often used for proxy objects, and is implemented with -forwardingTargetForSelector, +resolveInstanceMethod, and some similar methods. These are tools that allow classes to modify themselves at runtime, and is much less dangerous than modifying other classes (i.e. "swizzling").
It's also important to consider how all of this translates to Swift. In general, Swift has discouraged and restricted the use of runtime class manipulation, but it embraces (and improves) category-like extensions. By the time you're experienced enough to dig into the runtime, you will likely find it an even more obscure skill than it is today. But you will use extensions (Swift's version of categories) in every program.
A category allows you to add functionality to an existing class that you do not have access to source code for (System frameworks, 3rd party APIs etc). This functionality is possible by adding methods to a class at runtime.
For example lets say I wanted to add a method to NSString that swapped uppercase and lowercase letters called -swappedString. In static languages (such as C++), extending classes like this is more difficult. I would have to create a subclass of NSString (or a helper function). While my own code could take advantage of my subclass, any instance created in a library would not use my subclass and would not have my method.
Using categories I can extend any class, such as adding a -swappedString method and use it on any instance of the class, such asNSString transparently [anyString swappedString];.
You can learn more details from Apple's Docs

How to create a test to ensure no retain-cycle?

In one of mine project I have a quite complex data model.
I need a way to ensure that no retain cycle are created by me or by others colleagues and i want to use an automated approach.
There is a way to ensure that all the "dealloc" method are called?
You can try Static Analyzer (from menu : Product - Analyze or shorcut Shift+CMD+B). Or you create Unit Tests https://developer.apple.com/library/ios/documentation/ToolsLanguages/Conceptual/Xcode_Overview/UnitTestYourApp/UnitTestYourApp.html and check objects retainCount.
Leak instrument may help too : http://www.raywenderlich.com/2696/instruments-tutorial-for-ios-how-to-debug-memory-leaks , https://developer.apple.com/library/mac/documentation/developertools/conceptual/instrumentsuserguide/MemoryManagementforYouriOSApp/MemoryManagementforYouriOSApp.html
There is no way you can test such things automatically. Things you can do:
Have good coding standards and program architecture
Good architecture will prevent many retain cycles.
Be careful when using self in blocks (know when to use __weak id self).
Run Instruments and inspect leaks while your application is running
If you wish to do this you need to design & program it yourself.
For example you could:
Define "connection" as a strong reference to an instance of a class in your data model.
Define a protocol which provides either a "connected to" count method and one to return a connection by index or provides a connections iterator.
Have each class in your data model implement this protocol.
Now given a reference to your data model these protocol methods provide you with the "graph" (the objects are the nodes, the connections the arcs). Implement a cycle checking algorithm.
Now run the test at appropriate places during development & testing to check for accidental introduction of cycles.
You may be able to implement this without a protocol by using the facilities of the runtime, you can certainly given an arbitrary instance discover its ivars and whether an ivar is an object reference. You might get stuck though determining whether the ivar is strong or weak. While much more general this may be harder to implement, but once done...
HTH

What's the point of creating classes at runtime in Objective-C?

I've recently reread the interesting tutorial from Mike Ash about How to create classes at Objective-C Runtime
I has been a long time I am wondering where to apply this powerful feature of the language. I always see an overkill solution to most of the ideas that come to my mind, and I eventually proceed with NSDictionary. What are your cases of use of creating classes at runtime? The only one I see is an Obj-C interpreter... More ideas?
There's some possible options I see, when someone need to create class in runtime
To hide information about it (It won't help in most cases, but... you can)
To perform multiple-inheritance (If you really need it :)
Using your own language(i.e. some XML-like), that can be interpreted by your program, writted in Obj-C (Something like NSProxy, but even better.)
Creating some Dynamic-Class that can change it's behavior in runtime
In general.. There is some possible usages of this. But in real world, in default service applications there's no need to do this, actually:)
It could be used for example along Core Data or any API related to a database to create new classes of objects unknown at compilation time. However, I doubt this is used often, it's mostly the mechanism the system uses itself when it runs a program...
KVO, in the Cocoa frameworks, is implemented by dynamically creating "notifying" versions of your classes. See http://www.mikeash.com/pyblog/friday-qa-2009-01-23.html

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.

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;
}
}