Adventures in the transition from C to Cocoa.

Showing posts with label Objects. Show all posts
Showing posts with label Objects. Show all posts

Thursday, November 1, 2007

Best console log message ever

I was put between a rock and a hard place. Basically, I had to call a method on a class that isn't exported (i.e. I'm in plugin-space, and it needs to invoke something on an application-internal class that isn't exported). Through some trickery, I was able to get it working (man I love objective-C!). However, inserting the plugin into an application that doesn't have such a class results in an amazing console error that I've never seen before:


Nov 1 18:33:02 phendrana Photo Booth[33276]: *** NSInvocation: warning: object 0xfce0e0 of class 'specialInternalClass' does not implement methodSignatureForSelector: -- trouble ahead
Nov 1 18:33:02 phendrana Photo Booth[33276]: *** NSInvocation: warning: object 0xfce0e0 of class 'specialInternalClass' does not implement doesNotRecognizeSelector: -- abort


that "trouble ahead" part is awesome. I think it happens to any OC object that doesn't inherit from NSObject, but gets treated like it does. Fun stuff, that :)

Monday, August 6, 2007

Anti-aliases

Coming from a Linux background, I'm fairly comfortable with the idea of Symbolic Links. These are kind of like shortcuts on steroids; they transparently pose as files residing elsewhere, allowing all kinds of power (and problems).

Since OS X has some pretty strong Unix underpinnings, it came as no surprise to find that it supports Symbolic links out of the box. Unfortunately, the only way to create them is still with Terminal.app. No problem for me, being a keyboard cowboy, but for the average user it's a huge inconvenience.

Finder has a provision for making shortcuts, called aliases. This, unlike symbolic linking, is quite easy to use, and many non-programmer users use alias functionality. In fact, I even used aliases for a while, thinking they were simply symlinks renamed.

Then, along came a bug report to the Folder Movies Patch at kineme.net. Apparently, aliases were not symbolic links.

After a considerable amount of research, I discovered that aliases are Basically regular files. They report their length as zero bytes, and they store their data in a resource fork (oh how I loathe this concept...) To view the data, you can open a terminal, and type cat [alias file]/rsrc. You'll be greeted with some binary garbage, and some plain-text parts of the path to the real file.

So, how do we get a program to handle these peculiar files? Through some actions known as "Alias Resolution."

I won't bore you with all the exploration I did to come to the result, but here it is:


/* Multiple aliases in a path won't resolve here (we need to handle them one at a time)
so we need to prune off parts of the path recursively and try resolving those, then
rebuild the pruned off parts onto the resolved alias
*/
+ (NSString*) resolveAlias:(NSString *)filePath isFolder:(Boolean*)folder
{
unsigned char pathBuffer[4096];
FSRef fsRef;

if( FSPathMakeRef((const UInt8*)[filePath UTF8String], &fsRef,NO) == noErr )
{
Boolean isAlias = FALSE;
if( FSResolveAliasFile(&fsRef, TRUE, folder, &isAlias) == noErr && isAlias)
{
FSRefMakePath(&fsRef, pathBuffer, 4096);
return [NSString stringWithUTF8String:(const char*)pathBuffer];
}
}
else
{
//NSLog(@"FSPathMakeRef failed for %@\n",filePath);
// this fails when mutliple alises are in one path, so we prune and rebuild here
return [NSString stringWithFormat:@"%@/%@",
[self resolveAlias:[filePath stringByDeletingLastPathComponent] isFolder:folder],
[filePath lastPathComponent]
];
}
return nil;
}


This recursive method will take an NSString path, and resolve aliases as it goes. This means you can have an alias inside another alias, and they both get resolved correctly. It also takes a Boolean pointer to let you know if the ultimate target is a folder or not. It returns nil if there aren't any aliases in the path to resolve, otherwise it returns the resolved path, allowing you to access the target.

Monday, June 18, 2007

Retain and Release, and Object Creation

Objects in Objective-C maintain a counter to manage how many object point to the object in question. This counter modified by two methods, retain and release, and can be accessed directly by the retainCount method.

Each call to [object retain]; increments this counter, and each call to [object release]; decrements it. The retain/release counter starts at 1. When an object's count drop to 0, it deallocates itself. In Memory Management documentation, you'll find this behavior referred to as Reference Counting.

When an object deallocates itself, it uses its dealloc method. This method is comparable to a destructor in C++. Like C++, dealloc takes no arguments, and has no return value.

To create an object, you've probably noticed the [[object alloc] init]; sequence used. This uses two methods, alloc and init. alloc simply allocates memory. It is essentially the same as malloc() in C. init is used to initialize objects to a usable state. This is the job of a constructor in C++.

Writing our own init and dealloc methods requires a bit of work for things to work right. I'll present an example with both, and then explain the various parts and pieces.

#import <Foundation/Foundation.h>

@interface myObject: NSObject
{
@private
int count;
int refs;
}
-(id)init;
-(void)dealloc;
-(int)getCount;
-(void)incCount;
@end

@implementation myObject
-(id)init
{
self = [super init];
count = 0;
refs = 0;
printf("Running myObject's init method\n");
return self;
}

-(void)dealloc
{
printf("Running myObject's dealloc method\n");
[super dealloc];
}

-(int)getCount
{
return count;
}

-(void)incCount
{
++count;
}
@end

int main()
{
myObject *obj = [[myObject alloc] init];

printf("Object's count: %i\n",[obj getCount]);

[obj incCount];
[obj incCount];
[obj incCount];

printf("Object's count: %i\n",[obj getCount]);

[obj release];

return 0;
}


In this example, we have a simple class called myObject. This object implements a working init and dealloc, and little else.

First, an init method's declaration looks like this: -(id)init;. This means the return type is id, which is certainly not a standard C type. This type is similar to void* in C or C++. This basically means that we'll be returning a pointer to ourselves when the init method returns.

In the implementation of init we have some more magic. The first is self = [super init];. This line has two ideas; self and super. self is basically *this in C++. It's a reference to the object in question. So we're setting our object's reference to [super init]. This, unsurprisingly, uses super, another built-in variable that points to our class's parent class. Setting self to our object's parent's init method is required for proper inheritance.

Following all that stuff, init finishes with return self;. This returns a reference to our object so that the caller (main in this case) can access it.

In the dealloc method, we have a similar expression, [super dealloc];. This method does any necessary clean-up of our object using our class's parent's dealloc method. We are still responsible for any clean up we need to do ourselves (none in this example), but that's it.

Using init, dealloc, retain, and release allow us to start creating real complex classes, and do some basic memory management. There's still much more available in terms of memory management though, in the form of NSAutoReleasePools, but those are reserved for a future entry.

In case you were curious, the above program's output looks like this:
Running myObject's init method
Object's count: 0
Object's count: 3
Running myObject's dealloc method

Saturday, June 16, 2007

Object Antics

As with all Object-Oriented languages, Objective-C allows for some pretty handy trickery when it comes to objects, inheritance, and extensions. The terms used are fairly exclusive, but most of them have parallels.

In Cocoa Objects I briefly went over how to do basic inheritance. It is done by adding : InheritedObject on the @interface line, like this:

@interface myObject: NSObject


Objective-C does not allow multiple-inheritance. This means each object can only inherit from one object, and has only one super class, which we'll get into later.

Related to inheritance is an idea Objective-C refers to as Protocols. A protocol is comparable to a virtual class in C++, in that it defines what methods need to exist, but doesn't define how they work.

A protocol is defined very simply, as follows:
@protocol myProtocol
-(void) aMethod;
-(void) anotherMethod;
@end


For an object to adhere to this protocol, it must implement two methods, called aMethod and anotherMethod.

To indicate that an object adheres to a protocol, we use code like this:
@interface myClass: <myProtocol>


The stuff between the less-than and greater-than signs defines the protocol or protocols. If there are multiple protocols an object adheres to, they all appear between the brackets, in a comma-separated list, like this:
@interface myClass: <myProtocol, anotherProtocol>


Objects are meant to be dynamic in Objective-C. As such, NSObject provides a number of handy methods to help figure out what class an object inherits and what methods it uses.

#import <Foundation/Foundation.h>

@interface basicClass: NSObject
{
int basicInt;
}
@end

@interface mediumClass: basicClass
{
int mediumInt;
}
@end

@interface complexClass: mediumClass
{
int complexInt;
}
@end

@implementation basicClass
@end

@implementation mediumClass
@end

@implementation complexClass
@end

int main()
{
basicClass *bcObj = [[basicClass alloc] init];
mediumClass *mdObj = [[mediumClass alloc] init];
complexClass *cxObj = [[complexClass alloc] init];

if( [cxObj isKindOfClass: [mediumClass class]] == YES )
printf("cxObj is a kind of mediumClass\n");
else
printf("cxObj is not a kind of mediumClass\n");

if( [cxObj isKindOfClass: [basicClass class]] == YES )
printf("cxObj is a kind of basicClass\n");
else
printf("cxObj is note a kind of basicClass\n");

if( [bcObj isKindOfClass: [mediumClass class]] == YES )
printf("bcObj is a kind of mediumClass\n");
else
printf("bcObj is not a kind of mediumClass\n");

return 0;
}


As you can probably expect from this example, the output is this:
cxObj is a kind of mediumClass
cxObj is a kind of basicClass
bcObj is not a kind of mediumClass


We can use the isKindOfClass method to see if an object we get is of a particular kind. We can use the class method to get an object's class.

A related method is isMemberOfClass, which is used in exactly the same way as isKindOfClass. While isKindOfClass will return YES if any parent object is the specified class, isMemberOfClass will only return YES if the object in question's immediate parent (the super class) is the specified class. If we replace all all occurrences of isKindOfClass with isMemberOfClass in the example above, the output becomes:
cxObj is not a member of mediumClass
cxObj is note a member of basicClass
bcObj is not a member of mediumClass


Notice how complexClass is not a member of basicClass because basicClass is a grandparent object, not an immediate parent of complexClass.

There are a few other methods related to object methods, but they use selectors so I'll address those in a future entry. There are also methods we can use to determine if an object conforms to a given protocol. This will also be addressed later.

Up to this point, we've only dealt with @private for member variables, not methods. In fact, if you got adventurous and tried to mark some methods as private, you probably ran into some problems. This is because Objective-C has no syntax to create private member functions. The way around this is by using Categories. Categories are used to extend the functionality of a class by adding new methods. Simple usage looks like this:

#import 

@interface basicClass: NSObject
{
int basicInt;
}
@end

@implementation basicClass
@end

@interface basicClass (Extension)
-(void)extendedMethod;
@end

@implementation basicClass (Extension)
-(void)extendedMethod
{
printf("This method is in a category called \"Extension\"\n");
}
@end

int main()
{
basicClass *bcObj = [[basicClass alloc] init];

[bcObj extendedMethod];

return 0;
}


The (Extension) part defines the Category, which is called "Extension" in this case. The name can be pretty much anything though. However, each category name must be unique. Also, categories cannot add member variables, only methods.

Predictably, the output of the Category example above is:
This method is in a category called "Extension"


So, to create private member functions, all you need to do is add a Private category in the object's .m source file instead of the .h. This keeps the method inaccessible to callers outside of that .m file.

One last object trick available in Objective-C is the ability for a class to pose as its super class. This feature is aptly named "Posing." To have a class pose as another class, we use the poseAsClass method.
#import <Foundation/Foundation.h>

@interface basicClass: NSObject
{
int basicInt;
}
-(void) print;
@end

@implementation basicClass
-(void) print
{
printf("This is the basicClass method, uncooked.\n");
}
@end

@interface anotherClass: basicClass
@end

@implementation anotherClass
-(void) print
{
printf("This is anotherClass method.\n");
}
@end

int main()
{
basicClass *bcObj = [[basicClass alloc] init];
anotherClass *aObj = [[anotherClass alloc] init];

// after this, everything using basicClass will
// actually use anotherClass
[anotherClass poseAsClass: [basicClass class]];

basicClass *basicObject = [[basicClass alloc] init];

[bcObj print];
[aObj print];
[basicObject print];

return 0;
}


The output, demonstrating posing, looks like this:
This is the basicClass method, uncooked.
This is anotherClass method.
This is anotherClass method.


As you can see, the last two objects use the same print method, despite being different classes. This happens because of posing.

Friday, June 15, 2007

Cocoa Objects

Objects in Cocoa are very similar to objects in other languages such as C++ or Java. Their structure and syntax is very different though. While C++ and Java objects are essentially extensions (in syntax and organization) of the struct in C, Cocoa's objects are implemented in a completely different way, with a completely different syntax.

In C++, you'd create a class using some code kind of like this:

class myClass
{
private:
int anInteger;
float aFloat;
public:
void someMethod(float f);
int someOtherMethod(int i, float f);
};


and you'd have a class called myClass with 2 private member variables and 2 public member functions, or methods.

If you wanted, you could define the member functions inside the class declaration itself, or you could define them outside the class like this:

void myClass::someMethod(float f)
{
aFloat = f;
}


This would define the someMethod method of myClass. Because you can have different return types and argument types, C++ allows you to have different methods with the same name, as long as their types are different. This is a convention that is not allowed in Objective-C, as we shall shortly see.

In Objective-C, objects come in two parts, an interface and an implementation. These look completely weird to run-of-the-mill C/C++ Programmers, so brace yourself. This is an equivalent object in Objective-C.


@interface myObject
{
@private
int anInteger;
float aFloat;
}
-(void) someMethod:(float) f;
-(int) someOtherMethod:(int) i andFloat: (float) f;
@end


Right. So, we covered a lot right there. An object's interface is defined between @interface and @end. The name of the object is immediately after the @interface. Member variables are can be marked @public, @protected, or @private, with @protected being the default protection.

After the member variables, we declare the methods. The syntax here is pretty weird too. First, the method is declared either instance-scoped or class-scoped. Class-scoped is like static in C++. To declare a method as instance-scoped, use a minus sign: -. To declare it as class-scoped, use a plus sign: +.

Following the scope of the method, the return type is specified in parenthesis. Next comes the method name. If the method takes no parameters, we tack on a semicolon, and we're done. If it does, we tack on a colon, then specify the data type in parenthesis, followed by the variable name. If we have multiple parameters, it gets even more interesting.

-(int) someOtherMethod:(int) i andFloat: (float) f; uses two parameters. Instead of just having a list of arguments, Objective-C names them so that the user can keep track of what's going on. The andFloat part is doing just that. We don't strictly need to specify this part. We could simply use -(int) someOtherMethod:(int) i: (float) f; to make it look more like C. However, the names are pretty helpful, so I'd recommend using them.

As you've probably guessed by now, the @interface is similar the the class declaration. Thus, we're on to the @implementation.

@implementation myObject
-(void) someMethod:(float) f
{
aFloat = f;
}
-(int) someOtherMethod:(int) i andFloat: (float) f
{
anInteger = i;
aFloat = f;
}
@end


Not so surprisingly now, the @implementation defines the methods using almost the exact same syntax. It's pretty straightforward.

Typically the @interface goes in a .h header file. The @implementation goes in a .m source file. You can put them all in the same source file though if you want.

Inheritance is fairly common in Objective-C as well. In fact, it's practically essential for get to actually use our objects. Almost all the objects we create will extend NSObject. To do this, our interface line will look like this: @interface myObject: NSObject. Pretty close to C++'s method. It gets more complicated than this though, but that's for a future entry.

So now that we have basic objects at our disposal, it's time to talk about some rules regarding objects. First, objects cannot be statically allocated. If you try to, gcc will complain with an error like this: "error: statically allocated instance of Objective-C class." This is one of the reasons why we will almost always extend NSObject. The NSObject gives us a couple methods to dynamically create our objects. myObject *mo = [[myObject alloc] init]; is the typical way to allocate and initialize an object. The alloc method, as the name implies, allocates the necessary storage space, and init similarly initializes the object. This is in league with C++'s constructors.

Instead of delete, as we would use in C++ to free space used by an object, we use the release method, like this: [mo release];.

Before we continue, you've probably noticed that we call methods in a really different way. Instead of the expected myObject->method(args); syntax, we use [object method ... args]. To call a method with arguments from our object, it looks like this: [mo someMethod: 3.1415926];. You can probably guess how multiple parameters are handled, but here's another example just in case: [mo someOtherMethod: 42 andFloat: 1.234];.

So, to tie it all together into a working -- though useless -- example, here we go.

#import <Foundation/NSObject.h>
#import <stdio.h>

@interface myObject :NSObject
{
@private
int anInteger;
float aFloat;
}
-(void) someMethod:(float) f;
-(int) someOtherMethod:(int) i andFloat: (float) f;
@end

@implementation myObject
-(void) someMethod:(float) f
{
aFloat = f;
}
-(int) someOtherMethod:(int) i andFloat: (float) f
{
anInteger = i;
aFloat = f;
}
@end

int main(void)
{
myObject *mo = [[myObject alloc] init];

[mo someMethod: 3.1415926];
[mo someOtherMethod: 42 andFloat: 1.234];

[mo release];
return 0;
}


When compiling, be sure to use -framework Cocoa or else you'll get errors that are hard to understand. Like the following:

/usr/bin/ld: Undefined symbols:
.objc_class_name_NSObject
_objc_msgSend
collect2: ld returned 1 exit status


As an added bonus, you've been exposed to #import. You can safely assume that it's basically the same as #include -- in fact, you can often use them interchangeably -- except that #import makes sure to only include the file once without the #ifndef HEADER_H / #define HEADER_H / #endif stuff that litters the top and bottom C header files.

There you have it, the basics of Objective-C objects, and simple usage of Cocoa's framework.

Categories