Vincent Gable’s Blog

December 7, 2009

Dot Syntax Solution

Filed under: Cocoa,Design,Objective-C,Programming,Usability | , , , ,
― Vincent Gable on December 7, 2009

Surprisingly, the addition of dot syntax to Objective-C 2.0 has been a major source of controversy. I wonder if there’s some kind of Bike Shed effect at work here: the problem dot-syntax causes is trivial1; while the clarity it brings to code is minor. So it essentially boils down to aesthetics. (For the record, I like the dot, even with it’s current flaws, but I don’t believe it’s worth fighting for).

The Actual Problem

The problem is that when you see a.b = c; you don’t know if it’s:

  1. Assigning the b field of a struct to c. This basically compiles down to one move instruction.
  2. Invoking the -setB: method on an Objective-C object. By convention -setB: should update the b property of the object to hold the value c, and nothing else. But it might have side effects, or be really slow.

A Solution

Using a different symbol to access Objective-C properties would remove all ambiguity. Nobody would mistake a@b = c; as assigning to a C-struct. It’s clearly an Objective-C construct.

But personally, I’m not a big fan of the @ character. It’s ugly; it’s noisy; there’re just too many lines in it. I think U+25B8 ‘BLACK RIGHT-POINTING SMALL TRIANGLE’ would make a better choice,

obj▸property = value;

And since ‘▸’ can’t be part of a valid C identifier, you can basically preprocess your code with s/▸/./, then compile it with existing tools.

Of course, it doesn’t matter what character(s) is picked, so long as it’s clearly different from existing C syntax; and you have a way of replacing it with a . before building it.

1 I’ve heard experienced developers complain that dot-syntax = a steeper learning curve for newbies, and that it can be confusing, but I haven’t actually seen one come out and say ‘I spent X hours debugging a problem that I couldn’t see because of it’. The fact is, any situation that dot-syntax would obscure is already pathological. In the end I just can’t see dot-syntax mattering much.

April 19, 2009

Beware rangeOf NSString Operations

Filed under: Bug Bite,iPhone,Objective-C,Programming,Sample Code | , , , ,
― Vincent Gable on April 19, 2009

I have repeatedly had trouble with the rageOfNSString methods, because they return a struct. Going forward I will do more to avoid them, here are some ways I plan to do it.

Sending a message that returns a struct to nil can “return” undefined values. With small structs like NSRange, you are more likely to get {0} on Intel, compared to PowerPC and iPhone/ARM. Unfortunately, this makes nil-messaging bugs hard to detect. In my experience you will miss them when running on the simulator, even if they are 100% reproducible on an actual iPhone.

This category method has helped me avoid using -rangeOfString: dangerously,

@implementation NSString  (HasSubstring)
- (BOOL) hasSubstring:(NSString*)substring;
{
	if(IsEmpty(substring))
		return NO;
	NSRange substringRange = [self rangeOfString:substring];
	return substringRange.location != NSNotFound && substringRange.length > 0;
}
@end

I choose to define [aString hasSubstring:@""] as NO. You might prefer to throw an exception, or differentiate between @"" and nil. But I don’t think a nil string is enough error to throw an exception. And even though technically any string contains the empty string, I generally treat @"" as semantically equivalent to nil.

As I’ve said before,

A few simple guidelines can help you avoid my misfortune:

  • Be especially careful using of any objective-C method that returns a double, struct, or long long
  • Don’t write methods that return a double, struct, orlong long. Return an object instead of a struct; an NSNumber* or float instead of a double or long long. If you must return a dangerous data type, then see if you can avoid it. There really isn’t a good reason to return a struct, except for efficiency. And when micro-optimizations like that matter, it makes more sense to write that procedure in straight-C, which avoids the overhead of Objective-C message-passing, and solves the undefined-return-value problem.
  • But if you absolutely must return a dangerous data type, then return it in a parameter. That way you can give it a default value of your choice, and won’t have undefined values if an object is unexpectedly nil.
    Bad:
    - (struct CStructure) evaluateThings;
    Good:
    - (void) resultOfEvaluatingThings:(struct CStructure*)result;.

It’s not a bad idea to wrap up all the rangeOf methods in functions or categories that play safer with nil.

Thanks to Greg Parker for corrections!

March 17, 2009

Mutable @property and Copy Gotcha

Filed under: Bug Bite,Cocoa,Objective-C,Programming | , , ,
― Vincent Gable on March 17, 2009

If you have a @property for an object who’s name starts with NSMutable, and you use the copy declaration attribute, then the code that is synthesized for you is not correct. Because it uses copy, not mutableCopy, to do the copy during assignment, the value will not be mutable.

Here’s a demonstration,

@interface Gotcha : NSObject {
	NSMutableString *mutableString;
}
@property (copy) NSMutableString *mutableString;
@end
@implementation Gotcha
@synthesize mutableString;
@end

... Gotcha *x = [[[Gotcha alloc] init] autorelease]; x.mutableString = [NSMutableString stringWithString:@"I am mutable."]; [x.mutableString appendString:@" Look at me change."];

It crashes with the message,

*** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘Attempt to mutate immutable object with appendString:’

copy vs mutableCopy

The copy method returns an immutable copy of an object, even if the object is mutable. Eg the copy of an NSMutableString is an immutable NSString.

The mutableCopy method returns a mutable copy of an object, even if the object is not mutable. Eg., the mutableCopy of an NSString is an NSMutableString object.

@synthesize always uses copy in the setters it generates. That means an immutable copy will always be stored, even if an NSMutable object is given.

Workarounds

Apple says, ” …In this situation, you have to provide your own implementation of the setter method..” (To me, this isn’t as satisfying of an answer as a mutablecopy attribute. But it’s what Apple has chosen, so all we can do is file enhancement requests and trust their reasoning).

Another workaround is to make any property that is a mutable value readonly. If something is mutable, you can change it’s contents directly, so there is rarely a need to set it. For example, with the Gotcha object, it’s just as easy to say

[x.mutableString setString:@"New String"];

as

x.mutableString = [NSMutableString stringWithString:@"New String"];

Finally, you might consider using an immutable readwrite property. In my experience, immutable objects are generally safer, and often faster (I owe you an article on this, but there are plenty of articles on the benefits of immutability). I know this sounds like a smart-ass suggestion, and it won’t be a good answer much of the time. But it’s surprising how often things turn out not to need mutability once a design matures. Since reducing the mutability of an object often improves it, and it does work around the problem, it’s worth at least considering this solution.

Why not Just Use retain?

Changing the copy to retain well let you assign a mutable object, but I do not like the idea. My article, Prefer copy Over retain explains in detail. My biggest worry is aliasing,

NSMutableString *aLocalString = [NSMutableString string];
x.mutableString = aLocalString;
[x doSomething];
//aLocalString might have been changed by doSomething!
//
// 300 lines later...
//
[aLocalString appendString:@" now with more bugs!"];
//x has been changed too!

Using retain with NSMutable objects is asking for bugs.

December 20, 2008

Automatically Freeing Every @property

Filed under: Cocoa,MacOSX,Objective-C,Programming,Sample Code | , ,
― Vincent Gable on December 20, 2008

Here’s a category of NSObject that can simplify a dealloc method. It adds the method, setEveryObjCObjectPropertyToNil, that sets every property of the receiver to nil. (Properties that are readonly or not an Objective-C object are ignored.) This frees the underlying object, if the property is declared copy or retain; and it does no harm if it was declared assign.

If every ivar (member variable) in your object has a property declared for it, then your dealloc method can often be replaced by this macro, or it’s two-line expansion:

#define PROPERTY_ONLY_OBJECT_DEALLOC \
- (void) dealloc { \
   [self setEveryObjCObjectPropertyToNil]; \
   [super dealloc]; \
}

Limitations

Pointers

Any pointers (eg char*) will not be set to NULL; this includes pointers to an Objective-C object (eg NSError** outError). Of course NSObject* obj will be set to nil since it is considered an Objective-C object, even though it is written as if it were a pointer.

It is easy to build on setEveryObjCObjectPropertyToNil and have something that sets pointers to NULL as well. But I felt it was too risky. Sending a message to nil is valid, but dereferencing a NULL pointer is a “bus error” crash. [nil release]; does no harm, but free(NULL); is bad news. A settable @property that takes a raw pointer is a hybrid Objective-C, and “old”-C creature — I’ve never seen such a thing, so I’m wary of assuming that feeding it a NULL would be valid. Plus, opening the door to pointers means dealing with handles (pointers-to-pointers) and their ilk.

ivars

Any ivars (member variables) with no settable @property declared on them will not be freed. You can inspect your own ivars like you can @propertys (example), but it would not be safe to automatically release them. Some of them might be weak-links, meaning the object they point to was not sent a retain message. Weak-links are not terribly rare, for example objects always have a weak link to their delegate.

The Code

You will still need to download the source to get helper functions like SetterNameFromPropertyName() for this to actually run, but this should give you an idea of how it works:


@implementation NSObject(CleanUpProperties)
- (void) setEveryObjCObjectPropertyToNil;
{
   unsigned int i, propertyCount = 0;
   objc_property_t *propertyList = class_copyPropertyList([self class], &propertyCount);
   if(propertyList){
      for(i = 0; i < propertyCount; i++){
         const char *propertyAttrs = property_getAttributes(propertyList[i]);
         if(PropertyIsObjCObject(propertyAttrs) && PropertyIsSettable(propertyAttrs)) {
            NSString *setterName = SetterNameFromAttributes(propertyAttrs);
            if(!setterName)
               setterName = SetterNameFromPropertyName(property_getName(propertyList[i]));
            [self performSelector:NSSelectorFromString(setterName) withObject:nil];
         }
      }
      free(propertyList);
   }
}
@end


Download The Code


And please let me know how it works for you. I’ve started using setEveryObjCObjectPropertyToNil even if I only have one @property, because it means I’ll never forget to free one.

Warning (Update 2009-05-29)

Uli Kusterer gives a good reason not to use this code,

Don’t Use Accessors in Constructors or Destructors

This may sound a bit odd, but there is a reason to this madness. Constructors (i.e. -init methods in ObjC) and destructors (i.e. -dealloc or -finalize) are special methods: They are called before your object has fully been initialized, or may be called after it has already been partially torn down.

If someone subclasses your class, your object is still an object of that subclass. So, by the time your -dealloc method is called, the subclass has already been asked to do its -dealloc, and most of the instance variables are gone. If you now call an accessor, and that accessor does anything more than change the instance variable (e.g. send out notifications to interested parties), it might pass a pointer to its half-destructed zombie self to those other objects, or make decisions based on half-valid object state. The same applies to the constructor, but of course in reverse.

Now, some people that accessors should not be doing anything but change instance variables, but that is utter nonsense. If that was all they’re supposed to do, we wouldn’t need them. Accessors are supposed to maintain encapsulation. They’re supposed to insulate you from the internal details of how a particular object does its work, so you can easily revise the object to work in a completely different way, without anyone on the outside noticing. If an accessor could only change an instance variable, you would have very limited means to change this internal implementation.

Moreover, I don’t think Apple would have introduced Key-Value-Coding and Key-Value-Observing if they didn’t agree at least partially that it’s fine to do a bunch of things in response to an accessor being used to mutate an object.

Update 2009-11-29

I’m amused at the prevalent “Apple knows best” attitude. Bindings, garbage collection, NSOperationQueue, and so many other things, Apple has gotten wrong and burned me in the process. I always trust my own evaluation over their recommendations.

Mike Ash, Using Accessors in Init and Dealloc

Powered by WordPress