Is there a way to create linked list in objective c. I'm a newbie and so far I've researched in apple developer guides, there isn't any function predefined for linked list. Is doubly linked list same as linked list in objective-c?
Please help.
First thing to keep in mind is that Objective-C is C, it's just a lot more, too.
Next thing is that Objects are passed around as (essentially) pointers (which the compiler knows point to objects).
So you can certainly make and manage your own linked list, and you can do it with structs or objects. With objects (perhaps preferred), just create a #property in the class for the "next" object, and use it as you please. Similarly for a doubly-linked list, have a #property for previous.
Perhaps one of the best arguments against caring about liked lists in Objective-C is that usually you have the Cocoa Frameworks at hand, and there is such rich host of features which we used to have to implement ourselves with linked lists. For instance, the conceptually simple NSMutableArray, or NSDictionary are great examples of well-built components which usually spare us the need for linked lists. Going further, Core Data, etc...
A simple abstract linked list class might look like this:
#interface LinkedNode : NSObject
#property (nonatomic, strong) id nextNode;
#end
then you use it as you would expect:
id currentNode = myFirstNode;
do {
[currentNode someMessage];
}
while(currentNode = currentNode.nextNode);
Keep in mind that this is really no "better" than doing it with structs. For the "better" business, move to the Cocoa classes and implement at a "higher level", so-to-speak.
Please check my implementation of some of the common data structures like linked list, stack, binary search tree in objective C.
https://github.com/udaypatial/Data-Structures-in-Objective-C
Related
I am having a lot of repeated code throughout my app classes given that some properties & method are stable across all my views.
I am looking to extend whatever class I am working with so that it automatically inherit all properties and methods that I think should be common to those classes.
I looked into the apple guide on extending classes. But I am left confused in the terms of the level of heritance that I can achieve.
I've successfully created Categories on lets say a UIViewController. But that limits me to only be able to declare Methods. I can not declare Properties on my Category and call them in side my Category or in the Extended Class. I want to be able to declare Properties and use it inside and outside my Extended-Class.
Its my first time trying to extend a class in objective-c taking full advantage of heritance but I do not know if it is possible. Am I missing something?
As an example in the code below every time I try to instantiate activityIndicatorView inside my method _activityIndicator it wouldn't recognise it. I've tried #syntetize and #dynamic but it doesn't work
NOTE: I am seeking an answer based on how to achieve heritance of methods and propeties. not highlighting what categories cant do (as I already tried and know I cant have properties there)
My attempt went as far of
#import <UIKit/UIKit.h>
#interface UIViewController (customViewController1)
#property (strong, nonatomic) UIView *activityIndicatorView;
- (void) _activityIndicator;
#end
#import "UIViewController+customViewController1.h"
#implementation UIViewController (customViewController1)
- (void) _activityIndicator {
//......
}
Your question is too broad, plus it is not clear what your problem is. Yes, you can subclass in Objective-C.
This is all very well documented in Apple's document "Object-Oriented Programming with Objective-C", section "The Object Model", subsection "Inheritance".
Categories are a nice way to add functionality while at the same time conforming to an object oriented principle to prefer composition over inheritance.
Categories only add methods, you can't add variables to a class using categories. If the class needs more properties, then it has to be subclassed.
When you use the term “extend”, you're talking about creating a subclass. This is, IIRC, how the term is used in Java and some other languages.
Apple uses the term differently (as Hermann Klecker hinted in his first comment). They literally mean extending an existing class with more functionality (in the form of methods)—that's what categories do. This is the normal English definition; extending something in the real world generally does not create a new thing.
Objective-C supports subclasses, too; it just doesn't call them “extending” the superclass. It's called creating a subclass, which inherits from the superclass.
Strctly spoken you cannot add a property to an existing class any differnt than creating a subclass.
If you cannot halp yourself and subclassing is not an option, then you can extend the class with getters and setters for the property that you want to store within the class.
Instead of really storing it as a member/instance variable/property, which you can't do, you could store the object (it cannto be a scalar, must be an object) in the global space using objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy).
This is some sort of global dictionary with two keys, the key itself and the ojbect to which you want to associat the stored object to. In your case that is the object of the type of the exended class. The setter stores it there and the getter receives it from there using objc_getAssociatedObject.
You delete an association by sending nil as value to objc_setAssociatedObject
AFAIK retained associated objects (values) are released shortly after the object that holds the associateion (object) is deallocated.
For further details see the Ojbective-C Runtime Reference https://developer.apple.com/library/ios/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html
Just: I do not say that this is strictly following the OO paradigm. :-)
I'm reading the book "Programming in Objective C" and he explained not too much on the id type and didn't give much exercise on it, so I'm wondering how often do you use id and if programmers most of the time avoid it? (since he explained some issues with it)
I'm sure it's used, would be great if you can mention some cases it is the only solution..like real life programming cases from some kind of app development.
id is the universal type in Objective C. It can represent a * of any Objective-C type, such as NSString *, NSArray *, etc. The neat thing about Objective-C is that you can send messages to id, and if the object on the other end understands the message, it will get processed as usual without the sender having to know the real type.
It's commonly used when defining anything generic. For example, NSArray is an array of ids; it's up to the programmer to put a specific kind of object in the container (e.g. NSNumber, NSString, etc.). It's used in a lot of other places in Objective-C (such as when defining IBActions for the interface builder, when defining init methods, etc.).
id is the generic object type in Objective-C. It can hold any object.
one real world example: parsing json you wont know, if the root element is a array or a dictionary. But id would take them both.
I use it a lot, but often in conjunction with a protocol definition: id<NetworkPrinterProtocol>. This means that it should be an object of any kind but it does fulfill the NetworkPrinterProtocol. Often used for defining delegates.
see WP: Objective-C — Dynamic Typing
The id is kind of like a catch-all data type. It is used to hold values of any type.
Common uses are for the return type of init... methods. It's used by the collection classes since they can hold any object. See the various getter methods return values and the various methods for adding/setting objects in the mutable version of collection classes.
It's also used in combination with protocols when you need a reference to an object that can be any class but must adhere to a protocol. Examples include many of the delegate properties such as the UITableView delegate.
I'm fairly new to objective-c.
I'm trying to develop mostly experimental projects for a future development of a game app.
I would like to have suggestions on what I should use for the following purpose.
I'm trying to keep a group of objects somewhere (lets say something like an Array) in objective-c. I want that group of objects to be available everywhere in my application (different functions etc.) That group of objects has to be edit ready so NSArray (I guess) is out of the question? must be.
I'm struggling with concepts and still looking for the right way to do such a thing, tried to force some global arrays but I think that wasn't good practice.
Any help would be highly appreciated, thanks. (Please be kind enough to provide some further explanation on why I should use this -your suggestion- instead of something else. In that way you will help me grasp the idea better).
If it's a group of objects that needs to be shared throughout the entire application, and you want to shy away from global variables, then I think you have one good option:
By creating and storing the collection (which should be an NSMutableArray, an editable version of NSArray) in your application delegate, it can be accessible everywhere:
//MyAppDelegate.h
#property (nonatomic, retain) NSMutableArray *_editableArray;
//MyAppDelegate.m
- (void)applicationDidFinishLaunching {
_editableArray = [[NSMutableArray alloc] init];
// Add objects if you'd like
}
And then you can access it anywhere, like so:
// In other classes
((CastToYourAppDelegateClass *)[NSApp delegate]).editableArray;
Keep in mind that if you're going to be accessing/editing this array on any background thread (or using GCD) then you'll have to ensure that the access is properly synchronized. (Are you planning on doing so?)
Why not just to implement Singleton pattern for your shared object, that will have NSMutableArray as one of it's properties?
Would anyone be able to explain to me what data encapsulation in Objective-C is? I've been told that this an important concept of Objective-C but I don't see why...
Explain it to me as if I was 5 and then as if I was 25....
Thanks for your time,
~Daniel
From http://mobile.tutsplus.com/tutorials/iphone/learn-objective-c-2/ :
What we mean by data encapsulation is
that data is contained (so to speak)
by methods meaning to access it we
need to use methods. Some of you who
have programmed in other languages and
havenʼt heard of data encapsulation
may be wondering why we do things this
way. The answer is that by
encapsulating data, there is a nice
cushion between the developer of a
class and the user of a class. Because
the class methods manage and maintains
the attributes within the class, they
can more easily maintain data
integrity. Another major benefit is
that when a developer distributes his
class, the people using it donʼt have
to worry about the internals of the
class at all. A developer may update a
method to make it faster or more
efficient, but this update is
transparent to the user of the class
as he/she still uses the same method
with no change to his/her code.
In simple terms, the user is provided with what the developer wanted them to have, and "protects" everything else. The developer can change anything internal without the user having to rewrite their code.
If developers did not conform to data encapsulation, we would need to rewrite our code every time a new version of a library, code snippet, or an entire program was released.
Data encapsulation in Objective-C means that only the class itself should touch it's instance variables. Therefor you should always mark them as private, and only expose them through properties, as this:
#interface Foo : NSObject {
#private
int numberOfBars;
Baz* contentBaz;
}
#property(nonatamic, assign) int numberOfBars;
#property(nonatomic, retain) Baz* contentBaz;
#end
This means that the class can implement validation in it's setter methods. And even better if you use #synthesizeto generate your getter and setters than you need not even worry about the memory model of Cocoa at all (with the exception of releasing your ivars in dealloc).
A question that has pondered me for the last while. I am primarily a .net developer who dabbles in Objective-C for iPhone and Mac.
How do you go about sending "datasets" between methods in objective-c. For example in C# you can populate a custom class with data and pass it around in a List of type custom class. EG if you had a customer class you would just do something like:
List<Customer> customers = DataLayer.GetAllCustomers();
The only way I can see how this could be done in obj-c would be to populate an NSArray with custom objects? Is this an efficient way to do things? Any other recommendations? I am using sqlite as the database/data I want to return.
You're on the right track.
Cocoa's collection classes — which all have mutable an immutable variants — are:
NSArray: ordered, can contain an object multiple times
NSDictionary: unordered, mapping from keys to values, keys are copied
NSSet: unordered, can contain an object only once
NSCountedSet: unordered, can contain an object multiple times
The immutable variants help a lot with efficiency. The standard pattern for accessors of classes that have mutable variants is to copy rather than retain. This is codified in the #property mechanism, by using the copy attribute on the property:
// Department.h
#interface Department : NSObject
#property (readwrite, copy) NSSet *employees;
#end
This means that if you pass a mutable array to something that takes an array, it will be copied, and if you pass that to something else, it will be copied again. The trick is though that "copying" an immutable object really just retains it, so you only take a hit for that first copy. You probably want to make a copy that first time anyway so you don't pass a mutable array to something else, then mutate it behind the back of whatever you passed it to.
For Cocoa on Mac OS X, I'd also strongly encourage you to take a look at Core Data. It's an alternative to the "data set" pattern you might be used to from .NET/ADO/etc. With Core Data, you don't "get all customers" and then pass that collection around. Instead you query for the customers you care about, and as you traverse relationships of the objects you've queried for, other objects will be pulled in for you automatically.
Core Data also gets you features like visual modeling of your entities, automatic generation of property getters & setters, fine-grained control over migration from one schema version to another, and so on.