Best objective-c questions in April 2011

Why is this program faster in Python than Objective-C?

18 votes

I got interested in this small example of an algorithm in Python for looping through a large word list. I am writing a few "tools" that will allow my to slice a Objective-C string or array in a similar fashion as Python.

Specifically, this elegant solution caught my attention for executing very quickly and it uses a string slice as a key element of the algorithm. Try and solve this without a slice!

I have reproduced my local version using the Moby word list below. You can use /usr/share/dict/words if you do not feel like downloading Moby. The source is just a large dictionary-like list of unique words.

#!/usr/bin/env python

count=0
words = set(line.strip() for line in   
           open("/Users/andrew/Downloads/Moby/mwords/354984si.ngl"))
for w in words:
    even, odd = w[::2], w[1::2]
    if even in words and odd in words:
        count+=1

print count      

This script will a) be interpreted by Python; b) read the 4.1 MB, 354,983 word Moby dictionary file; c) strip the lines; d) place the lines into a set, and; e) and find all the combinations where the evens and the odds of a given word are also words. This executes in about 0.73 seconds on a MacBook Pro.

I tried to rewrite the same program in Objective-C. I am a beginner at this language, so go easy please, but please do point out the errors.

#import <Foundation/Foundation.h>

NSString *sliceString(NSString *inString, NSUInteger start, NSUInteger stop, 
        NSUInteger step){
    NSUInteger strLength = [inString length];

    if(stop > strLength) {
        stop = strLength;
    }

    if(start > strLength) {
        start = strLength;
    }

    NSUInteger capacity = (stop-start)/step;
    NSMutableString *rtr=[NSMutableString stringWithCapacity:capacity];    

    for(NSUInteger i=start; i < stop; i+=step){
        [rtr appendFormat:@"%c",[inString characterAtIndex:i]];
    }
    return rtr;
}

NSSet * getDictWords(NSString *path){

    NSError *error = nil;
    NSString *words = [[NSString alloc] initWithContentsOfFile:path
                         encoding:NSUTF8StringEncoding error:&error];
    NSCharacterSet *sep=[NSCharacterSet newlineCharacterSet];
    NSPredicate *noEmptyStrings = 
                     [NSPredicate predicateWithFormat:@"SELF != ''"];

    if (words == nil) {
        // deal with error ...
    }
    // ...

    NSArray *temp=[words componentsSeparatedByCharactersInSet:sep];
    NSArray *lines = 
        [temp filteredArrayUsingPredicate:noEmptyStrings];

    NSSet *rtr=[NSSet setWithArray:lines];

    NSLog(@"lines: %lul, word set: %lul",[lines count],[rtr count]);
    [words release];

    return rtr;    
}

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int count=0;

    NSSet *dict = 
       getDictWords(@"/Users/andrew/Downloads/Moby/mwords/354984si.ngl");

    NSLog(@"Start");

    for(NSString *element in dict){
        NSString *odd_char=sliceString(element, 1,[element length], 2);
        NSString *even_char=sliceString(element, 0, [element length], 2);
        if([dict member:even_char] && [dict member:odd_char]){
            count++;
        }

    }    
    NSLog(@"count=%i",count);

    [pool drain];
    return 0;
}

The Objective-C version produces the same result, (13,341 words), but takes almost 3 seconds to do it. I must be doing something atrociously wrong for a compiled language to be more than 3X slower than a scripted language, but I'll be darned if I can see why.

The basic algorithm is the same: read the lines, strip them, and put them in a set.

My guess of what is slow is the processing of the NSString elements, but I do not know an alternative.

Edit

I edited the Python to be this:

#!/usr/bin/env python
import codecs
count=0
words = set(line.strip() for line in 
     codecs.open("/Users/andrew/Downloads/Moby/mwords/354984si.ngl",
          encoding='utf-8'))
for w in words:
    if w[::2] in words and w[1::2] in words:
        count+=1

print count 

For the utf-8 to be on the same plane as the utf-8 NSString. This slowed the Python down to 1.9 secs.

I also switch the slice test to short-circuit type as suggested for both the Python and obj-c version. Now they are close to the same speed. I also tried using C arrays rather than NSStrings, and this was much faster, but not as easy. You also loose utf-8 support doing that.

Python is really cool...

Edit 2

I found a bottleneck that sped things up considerably. Instead of using the [rtr appendFormat:@"%c",[inString characterAtIndex:i]]; method to append a character to the return string, I used this:

for(NSUInteger i=start; i < stop; i+=step){
    buf[0]=[inString characterAtIndex:i];
    [rtr appendString:[NSString stringWithCharacters:buf length:1]];
}

Now I can finally claim that the Objective-C version is faster than the Python version -- but not by much.

Keep in mind that the Python version has been written to move a lot of the heavy lifting down into highly optimised C code when executed on CPython (especially the file input buffering, string slicing and the hash table lookups to check whether even and odd are in words).

That said, you seem to be decoding the file as UTF-8 in your Objective-C code, but leaving the file in binary in your Python code. Using Unicode NSString in the Objective-C version, but 8-bit byte strings in the Python version isn't really a fair comparison - I would expect the performance of the Python version to drop noticeably if you used codecs.open() to open the file with a declared encoding of "utf-8".

You're also making a full second pass to strip the empty lines in your Objective-C, while no such step is present in the Python code.

Mixing C# with Objective-C

12 votes

I would like to use larger body of C# code as a library for Objective-C (Cocoa) application.

I discovered MonoMac project which wraps Cocoa code, but I would rather have standard Cocoa application written in Objective-C, which can call wrapped C# code (other way around).

On Windows I am used to make C++/CLI project which wraps .NET code and exports plain old C interface for C/C++ based apps.

Is there some simple way to achieve this?

There is, obviously, no such language as C++/CLI on Mac OS. On Windows, C++/CLI actually compiles as managed code ran by the CLR, that runs native code; since on Mac OS Mono isn't integrated to the system, it's rather the other way around. Your app is native, and it can host managed code.

Mono exposes functions to host a CLR virtual machine inside a process. Since CLR classes aren't directly exposed to your C code, you'll be able to call methods of objects through reflection-like calls.

There is documentation on how to embed Mono into an application on the official site. Since you're not interested in running .NET programs directly, you should rather read the "Invoking Methods in the CIL Universe" section. On Mac OS, you'll want to link against the Mono framework from your /Library/Frameworks folder, instead of using pkg-config.

This really shouldn't replace an actual reading of the above document, but the following can be seen as a guide as to what to expect:

#include <glib/glib.h>
#include <mono/jit/jit.h>
#include <mono-metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>

// create an app domain
// http://en.wikipedia.org/wiki/Application_Domain
MonoDomain* domain = mono_jit_init("Domain");

// mandatory Cocoa call to show that Mono and ObjC work together
NSBundle* mainBundle = [NSBundle mainBundle];
NSString* dll = [mainBundle pathForResource:@"your-dll" ofType:@"dll"];

// load the referenced assembly in our domain
MonoAssembly* assembly = mono_domain_assembly_open(domain, [dll UTF8String]);
MonoImage* image = mono_assembly_get_image(assembly);

// find the class we want to wrap and create an instance
MonoClass* classHandle = mono_class_from_name(image, "Name.Space", "YourClass");
MonoObject* object = mono_object_new(domain, classHandle);

// this calls the default, argument-less ctor
// for more complex constructors, you need to find the method handle and call it
// (helpful hint: constructors are internally called ".ctor", so the description
// string will look like "Namespace.Class..ctor()")
mono_runtime_object_init(object);

// get a method handle to whatever you like
const char* descAsString = "Your.NameSpace.YourClass:YourMethod()";
MonoMethodDesc* description = mono_method_desc_new(descAsString);
MonoMethod* method = mono_method_desc_search_in_class(description, classHandle);

// call it
void* args[0];
mono_runtime_invoke(method, object, args, NULL);

// when you're done, shutdown the runtime by destroying the app domain
mono_jit_cleanup(domain);

If you don't find this very appealing, you may want to go the other way around, as you mentioned, and look into MonoMac, which provides .NET bindings to a large portion of the APIs you may want to use in a Mac application (Cocoa, CoreImage, CoreAnimation, etc) and means to create your own bindings.

iPad: new 4/5 finger multitasking gestures - when is the app's screenshot taken?

7 votes

When my app resigns activation it covers the current view with a black view to prevent iOS from taking a screenshot of the potentially sensitive document being shown.

When pushing the app to background this works fine. The screenshot is taken AFTER didEnterBackground. Using multitasking gestures to switch back shows the black view.

However with the new 4/5 finger gestures if you swipe left or right, first "resign activation" is triggered and then "did enter background" but the screenshot seems to be taken BEFORE these events. How to prevent it in that case?

If I understand correctly, you're trying to avoid this problem:

http://software-security.sans.org/blog/2011/01/14/whats-in-your-ios-image-cache-backgrounding-snapshot/

And the issue is that the behavior doesn't match what Apple documents here:

http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/CoreApplication/CoreApplication.html#//apple_ref/doc/uid/TP40007072-CH3-SW21

If that's true, then this definitely sounds like a bug -- but you do realize the gesture you mentioned is apparently a developer feature that's not available to the public (and under NDA)?

I'd do the following:

  1. Sumbit a bug report - http://bugreport.apple.com/

  2. Ask on the Apple Developer Forums (and include the bug number). People can speak freely there, and it's possible that an Apple developer will respond or at least notice your post (and hopefully prioritize the bug).

  3. Finally, if you really want a response from Apple, then problems like this are a perfect use for your technical support incidents. You get 2 of these per year included with your ADC membership: http://developer.apple.com/support/resources/technical-support.html

What's the difference between a method and a selector?

6 votes

What the difference between a method, a selector and a message in Objective-C?

This is a great question.

  • Selector - a Selector is the name of a method. You're very familiar with these selectors: alloc, init, release, dictionaryWithObjectsAndKeys:, setObject:forKey:, etc. Note that the colon is part of the selector; it's how we identify that this method requires parameters. Also (though it's extremely rare), you can have selectors like this: doFoo:::. This is a method that takes three parameters, and you'd invoke it like [someObject doFoo:arg1 :arg2 :arg3]. There's no requirement that there be letters before each part of the selector components. As I said, this is extremely rare, and you will not find it used in the Cocoa frameworks. You can work with selectors directly in Cocoa. They have the type SEL: SEL aSelector = @selector(doSomething:) or SEL aSelector = NSSelectorFromString(@"doSomething:");

  • Message - a message is a selector and the arguments you are sending with it. If I say [dictionary setObject:obj forKey:key], then the "message" is the selector setObject:forKey: plus the arguments obj and key. Messages can be encapsulated in an NSInvocation object for later invocation. Messages are sent to a receiver. (ie, the object that "receives" the message).

  • Method - a method is a combination of a selector and an implementation (and accompanying metadata). The "implementation" is the actual block of code; it's a function pointer (an IMP). An actual method can be retrieved internally using a Method struct (retrievable from the runtime).


Some other related things that you didn't ask for:

  • Method Signature - a method signature represents the data types returned by and accepted by a method. They can be represented at runtime via an NSMethodSignature and (in some cases) a raw char*.

  • Implementation - the actual executable code of a method. Its type at runtime is an IMP, and it's really just a function pointer. iOS 4.3 includes a new ability to turn a block into an IMP. This is really cool.

One of the fun things to realize is that the name of a method (the selector) is distinct from the implementation of the method (the IMP). This means that you can swap them around, if you're feeling daring. You can also add and remove methods at runtime, because all you're doing is editing an entry in a hash table: the key is the selector, and the value is the IMP of the method. This allows you to do some really crazy and trippy stuff. It's not for the faint of heart. :)

What's the harm of property override in Objective-C ?

6 votes

There are several situations where you might override a super class's property.

  1. You declare a property with the same name and same attribute of its superclass'.(since if you change the attribute you can get an compiler warning).And you can synthesieze with an ivar that you create. What's the use of this? Or what's the harm can it do?

  2. If a superclass declares a property in a class extension (a category with no name), then it might not be in the header file. If you don't know that property from the header file, you can declare the same name property with what ever attribute or class you want. But the setter/getter method will override the ones for that "secret property". I think this can only do harm. But since you don't know from the header file, how can you avoid this?

  3. You can declare a property in the header file as "readonly" and in class extension redeclare it as "readwrite". I think this is the situation that it can do good.

Is my understanding about these situations right? And I don't know what good the first and second situations can do. But if I want to avoid the first situation, I can check if the subclass already has the property before I declare it. But if the property is not in the public header file, as in the second situation, I just don't know what to do.

There is a proper place for each of the situations you have mentioned, with varying frequency of use out in the wild. You just have to use care not to step on yourself. I'll illustrate with example's I have personally come across.

Subclassing to intentionally override a property
In this situation, like Joe mentioned, you had better know exactly what you're doing and have no other options before you override a property. I've personally found it's usually sufficient to override a single setter or getter for an already existing property to achieve customization, rather than re-declare and synthesize the property. For example, consider a specialized UIView subclass that only makes sense to have a UIClearColor background. To enforce this, you may override -setBackgroundColor: to just print a warning message and then not call super's implementation. I'll say I've never had a reason to completely override a property, but I won't say it couldn't be a useful tool in some case where you need to completely hijack an existing property.

Private Property
This is more useful than you give it credit for. The alternative to a private property is a plain ol' ivar, which we're all familiar with. If this is an ivar that's changing with some frequency, you'll end up with chunks of code that look like this:

[_myIvar release], _myIvar = nil;

or:

[_myIvar release];
_myIvar = [someValue retain];

While it doesn't look too bad, memory management boilerplate code like this gets really old, really fast. Alternatively, we could implement the above example as a private property, with retain semantics. This means, no matter what, we just have to:

self.myIvar = someValue;

Which is much easier on the eyes and fingers after awhile. You're correct in noting that, since this property is invisible to the rest of the universe, it could accidentally be overridden by a subclass. This is an inherent risk when developing in Objective-C, but you can take measures to make the risk vanishingly small. These measures are variations on modifying the name of your private properties in a predictable manner. There are infinite roads you could take here: say, for example, you make it a personal policy to prepend your private property names with your initials and an underscore. For me, I would get something like mw_ivar, and corresponding -setMW_ivar: and -mw_ivar accessors. Yes, it's is statistically possible that someone could come along and accidentally override that name, but really, they won't. Especially if you have a way of publishing your practices to those who may use your code. And, I can safely say that Apple has not gone around and made private properties that were mangled in such a way, so you'll be safe on that front as well.

Publicly Readonly, Privately Readwrite
This is just standard practice. You're right that it's useful, and also that it's not dangerous since the property is in the header. Anyone accidentally overriding it has only themselves to blame.

Calling -retainCount Considered Harmful

6 votes

Or, Why I Didn't Use retainCount On My Summer Vacation

This post is intended to solicit detailed write-ups about the whys and wherefores of that infamous method, retainCount, in order to consolidate the relevant information floating around SO.*

  1. The basics: What are the official reasons to not use retainCount? Is there ever any situation at all when it might be useful? What should be done instead?** Feel free to editorialize.

  2. Historical/explanatory: Why does Apple provide this method in the NSObject protocol if it's not intended to be used? Does Apple's code rely on retainCount for some purpose? If so, why isn't it hidden away somewhere?

  3. For deeper understanding: What are the reasons that an object may have a different retain count than would be assumed from user code? Can you give any examples*** of standard procedures that framework code might use which cause such a difference? Are there any known cases where the retain count is always different than what a new user might expect?

  4. Anything else you think is worth metioning about retainCount?


* Coders who are new to Objective-C and Cocoa often grapple with, or at least misunderstand, the reference-counting scheme. Tutorial explanations may mention retain counts, which (according to these explanations) go up by one when you call retain, alloc, copy, etc., and down by one when you call release (and at some point in the future when you call autorelease).

A budding Cocoa hacker, Kris, could thus quite easily get the idea that checking an object's retain count would be useful in resolving some memory issues, and, lo and behold, there's a method available on every object called retainCount! Kris calls retainCount on a couple of objects, and this one is too high, and that one's too low, and what the heck is going on?! So Kris makes a post on SO, "What's wrong with my memory management?" and then a swarm of <bold>, <large> letters descend saying "Don't do that! You can't rely on the results.", which is well and good, but our intrepid coder may want a deeper explanation.

I'm hoping that this will turn into an FAQ, a page of good informational essays/lectures from any of our experts who are inclined to write one, that new Cocoa-heads can be pointed to when they wonder about retainCount.

** I don't want to make this too broad, but specific tips from experience or the docs on verifying/debugging retain and release pairings may be appropriate here.

***In dummy code; obviously the general public don't have access to Apple's actual code.

The basics: What are the official reasons to not use retainCount?

Autorelease management is the most obvious -- you have no way to be sure how many of the references represented by the retainCount are in a local or external (on a secondary thread, or in another thread's local pool) autorelease pool.

Also, some people have trouble with leaks, and at a higher level reference counting and how autorelease pools work at fundamental levels. They will write a program without (much) regard to proper reference counting, or without learning ref counting properly. This makes their program very difficult to debug, test, and improve -- it's also a very time consuming rectification.

The reason for discouraging its use (at the client level) is twofold:

1) The value may vary for so many reasons. Threading alone is reason enough to never trust it.

2) You still have to implement correct reference counting. retainCount will never save you from imbalanced reference counting.

Is there ever any situation at all when it might be useful?

You could in fact use it in a meaningful way if you wrote your own allocators or reference counting scheme, or if your object lived on one thread and you had access to any and all autorelease pools it could exist in. This also implies you would not share it with any external APIs. The easy way to simulate this is to create a program with one thread, zero autorelease pools, and do your reference counting the 'normal' way. It's unlikely that you'll ever need to solve this problem/write this program for anything other than "academic" reasons.

As a debugging aid: you could use it to verify that the retain count is not unusually high. If you take this approach, be mindful of the implementation variances (some are cited in this post), and don't rely on it. Don't even commit the tests to your SCM repository.

This may be a useful diagnostic in extremely rare circumstances. It can be used to detect:

  • Over-retaining: An allocation with a positive imbalance in retain count would not show up as a leak if the allocation is reachable by your program.

  • An object which is referenced by many other objects: One illustration of this problem is a (mutable) shared resource or collection which operates in a multithreaded context - frequent access or changes to this resource/collection can introduce a significant bottleneck in your program's execution.

  • Autorelease levels: Autoreleasing, autorelease pools, and retain/autorelease cycles all come with a cost. If you need to minimize or reduce memory use and/or growth, you could use this approach to detect excessive cases.

From commentary with Bavarious (below): a high value may also indicate an invalidated allocation (dealloc'd instance). This is completely an implementation detail, and again, not usable in production code. Messaging this allocation would result in a error when zombies are enabled.

What should be done instead?

If you're not responsible for returning the memory at self (that is, you did not write an allocator), leave it alone - it is useless.

You have to learn proper reference counting.

For a better understanding of release and autorelease usage, set up some breakpoints and understand how they are used, in what cases, etc. You'll still have to learn to use reference counting correctly, but this can aid your understanding of why it's useless.

Even simpler: use Instruments to track allocs and ref counts, then analyze the ref counting and callstacks of several objects in an active program.

Historical/explanatory: Why does Apple provide this method in the NSObject protocol if it's not intended to be used? Does Apple's code rely on retainCount for some purpose? If so, why isn't it hidden away somewhere?

We can assume that it is public for two primary reasons:

1) Reference counting proper in managed environments. It's fine for the allocators to use retainCount -- really. It's a very simple concept. When -[NSObject release] is called, the ref counter (unless overridden) may be called, and the object can be deallocated if retainCount is 0 (after calling dealloc). This is all fine at the allocator level. Allocators and zones are (largely) abstracted so... this makes the result meaningless for ordinary clients. See commentary with bbum (below) for details on why retainCount cannot be equal to 0 at the client level, object deallocation, deallocation sequences, and more.

2) To make it available to subclassers who want a custom behavior, and because the other reference counting methods are public. It may be handy in a few cases, but it's typically used for the wrong reasons (e.g. immortal singletons). If you need your own reference counting scheme, then this family may be worth overriding.

For deeper understanding: What are the reasons that an object may have a different retain count than would be assumed from user code? Can you give any examples*** of standard procedures that framework code might use which cause such a difference? Are there any known cases where the retain count is always different than what a new user might expect?

Again, a custom reference counting schemes and immortal objects. NSCFString literals fall into the latter category:

NSLog(@"%qu", [@"MyString" retainCount]); 
// Logs: 1152921504606846975

Anything else you think is worth mentioning about retainCount?

It's useless as a debugging aid. Learn to use leak and zombie analyses, and use them often -- even after you have a handle on reference counting.

Is a private synthesized property an oxymoron?

6 votes

After going through a beginner's iPhone developer book and reading sample code online, I've noticed that most Objective C programmers synthesize nearly every instance variable. Some variables are convenient to snythesize, but most should not when honoring the object oriented principle of encapsulation. The worst are synthetized properties marked as private. A C++ programmer trying to use someone else's code will read the public fields and methods in the header file. They will skip the private variables. This C++ programmer will not know that you intended the private properties to be used in some meaningful way.

Take a look at this sample template on lazy table image loading provided by Apple:

Header

@interface ParseOperation : NSOperation <NSXMLParserDelegate>

{
@private
    id <ParseOperationDelegate> delegate;
    NSData          *dataToParse;
    NSMutableArray  *workingArray;
    AppRecord       *workingEntry;
    NSMutableString *workingPropertyString;
    NSArray         *elementsToParse;
    BOOL            storingCharacterData;
}

Source

@interface ParseOperation ()
@property (nonatomic, assign) id <ParseOperationDelegate> delegate;
@property (nonatomic, retain) NSData *dataToParse;
@property (nonatomic, retain) NSMutableArray *workingArray;
@property (nonatomic, retain) AppRecord *workingEntry;
@property (nonatomic, retain) NSMutableString *workingPropertyString;
@property (nonatomic, retain) NSArray *elementsToParse;
@property (nonatomic, assign) BOOL storingCharacterData;
@end

@implementation ParseOperation
@synthesize delegate, dataToParse, workingArray, workingEntry, workingPropertyString, elementsToParse, storingCharacterData;

Now I know this is not C++ and we shouldn't assume all C++ practices should be honored in Objective C. But Objective C should have good reasons to stray away from general programming practices.

  1. Why are all the private ivars synthesized? When you look at the project as a whole, only NSMutableArray *workingArray is used by outside classes. So none of the other ivars should have setters and getters.
  2. Why are very sensitive ivars synthesized? For one, now that id delegate has a setter, the user of this object can switch the delegate in middle of the XML parsing, something that doesn't make sense. Also, NSData *dataToParse is raw XML data retrieved from the network. Now that it has a setter, the user of this object can corrupt the data.
  3. What's the point of marking everything private in the header? Since all ivars are are synthesized to have getters/setters, they are effectively public. You can set them to anything you want and you can get their value whenever you want.

I follow the idiom modeled by this example in many of my classes, so I can try to explain my own justification for this practice.

The properties in this example are declared in a class extension in the .m file. This makes them effectively private. Any attempt to access these properties from another class will cause a "Property not found" error upon compilation.

For developers coming from other languages, it may seem strange to synthesize getters and setters for private instance variables. Indeed, there is only one reason why I do this. When used consistently, synthesized properties can simplify memory management and help avoid careless mistakes that can lead to bugs. Here are a couple of examples:

Consider this:

self.workingPropertyString = [NSMutableString string];

versus this:

workingPropertyString = [[NSMutableString string] retain];

Many developers would claim that these two assignments are functionally equivalent, but there's an important difference. The second assignment leaks memory if workingPropertyString was already pointing at a retained object. To write code functionally equivalent to the synthesized setter, you'd have to do something like this:

NSMutableString *newString = [NSMutableString string];
if (workingPropertyString != newString) {
    [workingPropertyString release];
    workingPropertyString = [newString retain];
}

This code avoids leaking any existing object that the instance variable may be pointing to, and it safely handles the possibility that you may be re-assigning the same object to the instance variable. The synthesized setter does all of this for you.

Of course we can see that (workingPropertyString != newString) will always be true in this case, so we could simplify this particular assignment. In fact in most cases you can probably get away with a simple direct assignment to an instance variable, but of course it's the exceptional cases that tend to create the most bugs. I prefer to play it safe and set all my object instance variables through synthesized setters. All my instance object assignments are simple one-liners that look like this:

self.foo = [Foo fooWithTitle:@"The Foo"];

or this:

self.foo = [[[Foo alloc] initWithTitle:@"The Foo"] autorelease];

This simplicity and consistency gives my feeble brain less stuff to think about. As a result I almost never have bugs related to memory management. (I'm aware that the autorelease idiom could theoretically consume excessive memory in a tight loop, but I have yet to encounter that issue in practice. If I ever do, it's a simple case to optimize.)

One other thing I like about this practice is that my dealloc methods all look like this:

- (void)dealloc {
    self.delegate = nil;
    self.dataToParse = nil;
    self.workingArray = nil;
    self.workingEntry = nil;
    self.workingPropertyString = nil;
    self.elementsToParse = nil;
    [super dealloc];
}

EDIT: Daniel Dickison pointed out some risks to using accessors in dealloc that I hadn't considered. See the comments.

where every object property is simply set to nil. This simultaneously releases each retained property while setting it to nil to avoid certain crashes due to EXC_BAD_ACCESS.

Note that I've set self.delegate = nil; even though that property was declared as (nonatomic, assign). This assignment wasn't strictly necessary. In fact, I could do away with properties for my (nonatomic, assign) objects altogether, but again I've found that applying this idiom consistently across all my instance variables gives my brain less to think about, and further reduces the chance that I'll create a bug through some careless mistake. If necessary I can simply flip a property from (nonatomic, assign) to (nonatomic, retain) without having to touch any memory management code. I like that.

One could also use consistency as an argument for synthesizing properties for private scalar variables, as your example has done in the case of BOOL storingCharacterData;. This practice ensures that every instance variable assignment will look like self.foo = bar;. I don't usually bother to create private scalar properties myself, but I can see some justification for this practice.

XCode 4 Archive/IPA Error: "The operation couldn’t be completed. No such file or directory"

6 votes

I've found various proposed solutions to this problem on this internet, but none of them work for me. Does anyone know why this might be happening?

http://answers.unity3d.com/questions/15294/xcode-build-and-archive-error-no-such-file-or-directory

http://blog.joshschumacher.com/2011/04/06/xcode4-the-operation-couldn%E2%80%99t-be-completed-no-such-file-or-directory/

I've tried archiving with every combination of coding signing vs not using code signing, and I've tried using every combination of provisioning profiles, but I still get the same error every time.

I'm very confused as to why I'd even be getting an error like this when trying to save a file. I'm using XCode 4, my application builds for archive fine. In fact, I can even upload my application to itunesconnect (and it was accepted!). I just can't create an IPA for sharing and beta testing before submission.

Any ideas?

The error message The Error

Right before I get the error Right before I get the error

After much frustration, I filed a developer support request with Apple. The technician I spoke with was able to save my archive as an .ipa on her computer -- the exact same archive that I was not able to save on mine, which pointed to a possible bug in my system (and from the sounds of it, many other people's).

She recommended that I uninstall and reinstall XCode and the developer tools, and that worked!

Here were her uninstall instructions:

  • Make sure that your machine is running the latest Mac OS X (10.6.7) and iTunes.
  • Run the following command in the Terminal application to uninstall your SKD: sudo <Xcode>/Library/uninstall-devtools --mode=all (where <Xcode> is the path to the directory that contains your SDK.)
  • Drag your <Xcode> to the trash and restart your machine
  • Re-download and install Xcode (4.0.2) from the iOS Dev Center. Make sure that the System Tools, UNIX Development, Essentials packages in the Custom Install pane are selected before installing it.

How to close a window programmatically in Cocoa Mac ?

5 votes

Hi, How can I programmatically close a window in cocoa mac ? I have opened a second window/xib from the first window/xib using button click. I need to close the first window/xib programmatically on opening or clicking the button. How can I do that?

Apple has some useful sample code on Nib Loading. It doesn't directly address this question however; the following code does.

@interface CloseWindowAppDelegate : NSObject <NSApplicationDelegate> {
    NSWindow *window;
    IBOutlet NSWindow * secondWindow;
    NSNib * secondNib;
}

@property (assign) IBOutlet NSWindow *window;

- (IBAction)openSecondWindow:(id)sender;

- (IBAction)closeSecondWindow:(id)sender;

@end

#import "CloseWindowAppDelegate.h"

@implementation CloseWindowAppDelegate

@synthesize window;

- (IBAction)openSecondWindow:(id)sender {
    secondNib = [[NSNib alloc] initWithNibNamed:@"SecondWindow" bundle:nil];
    [secondNib instantiateNibWithOwner:self topLevelObjects:nil];
    [secondWindow makeKeyAndOrderFront:nil];

}

- (IBAction)closeSecondWindow:(id)sender {
    [secondWindow close];
    [secondNib release];

}

@end

Way to get beginGestureWithEvent/endGestureWithEvent if window isn't frontmost

5 votes

Is there a way to get

- (void)beginGestureWithEvent:(NSEvent *)event

and

- (void)endGestureWithEvent:(NSEvent *)event

calls to a view even if the containing window is in the background? It seems these calls are only delivered to windows if they are key.

In general no. In Leopard and SnowLeopard, gestures are intended to target only the foreground window. As you discovered, the window server will not even send gesture events to background applications.

You could instal an event tap, but those events don't look exactly their the NS equivalents. All the data is there, though, if you really want to dig into it.

Please file a radar asking for this along with why this would be useful.

play two video in iPhone simultaneously.

5 votes

Hi All,

I want to play two video in iPhone simultaneously.

There are two way to play video in iphone, One is use AVQueuePlayer. but in this controller I don't get how get the video playing is completed and how to restart video again.

Another way is MPMoviePlayerController . but in this controller I don't get how to seek video at particular time and also it is not able to play two video simultaneously as the AVQueuePlayer is able to play.

as a solution i am using AVQueuePlayer to play video and but can any one help me to restart video and get method to detect end point of the video. or know any other api to so this

Thanks in advance.

Hi ,

I have found the solution to play two video . You can use AVQueuePlayer to play video. Using this controller you can play two video at the same time .

Lazy Image Drawing

5 votes

I have an object that needs to draw into a graphic context on demand, however, the content needs time to render and might not be available when the objects draw method is invoked.

How is this generally accomplished? Store a reference to the graphics context or view that requested drawing and draw it there delayed when the objects internal representation is completely rendered?

Or are there other standard cocoa mechanisms to handle this (for instance NSImage does lazy drawing when initialized with a NSURL)?

Clarifications:


  • I am on MacOS, not iOS
  • Using some NSViews -setNeedsDisplay: is not the answer I am looking for (NSImage doesn't rely on -setNeedsDisplay:)

You should look into using NSOperation; either an NSInvocationOperation, if you have a specific object doing the rendering, or NSBlockOperation, if the rendering is simple enough to fit into a single function.

If you can start rendering before you actually get to your view's drawRect:, then do that (maybe your app delegate starts the process right at launch). Otherwise, check in the drawRect: whether the content is available yet; if not, start the operation and continue with the other drawing. When the rendering object finishes its work, it will probably either post a notification or, if you give it a reference back to the view, call setNeedsDisplay:

Along the lines of your last sentence, you could also consider your rendering object being able to return a partially-rendered image. I'm not certain of the nature of your rendering, but it may be possible to get the results at certain points (the end of every n loops, or every n lines of pixels), stuff that into a separate NSImage of the same size as the final image (padding at the end if necessary), and make this partial image available to the view for drawing.

UPDATE: An NSImage doesn't "rely on" setNeedsDisplay: or having a view reference because it doesn't represent a piece of the screen. All it does is contain the data for an image; it can only draw itself inside a view, which is then "displayed" -- actually painted on the screen. When you use initByReferencingURL:, it stores the URL, and then when another object (like a view that contains the image and needs to be displayed) asks it for its contents, it does what it would've done if you had used initWithURL:, which is open the file and read its contents into memory. It doesn't draw lazily, though; it only draws into the view that wants it, when that view is drawing.

Subclassing NSImage to implement your own lazy loading or lazy rendering may not be easy; it uses helper classes that I believe are part of a class cluster, which is why I suggest having a "renderer" object which contains and returns an NSImage.

MORE:

A custom view's drawRect:

- (void)drawRect:(NSRect)dirtyRect {
    NSLog(@"Entered: %@", NSStringFromSelector(_cmd));
    // Use a nice big image of the Milky Way -- this is about 5MB
    NSImage * lazyImage = [[[NSImage alloc] initByReferencingURL:
                            [NSURL URLWithString:@"http://www.eso.org/public/archives/images/original/milkyway.jpg"]]
                           autorelease];
    NSLog(@"Image instantiated.");
    [lazyImage drawInRect:[self bounds] fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
    NSLog(@"Image drawn");  // 2 minutes later; sometimes 3 in my testing
    [[NSColor yellowColor] set];
    [[NSBezierPath bezierPathWithRect:NSInsetRect([self bounds], 4, 4)] stroke];
    NSLog(@"Bezier path drawn; exiting drawRect.");
}

The log output from this; notice that the instantiation is very quick, but the loading and drawing takes two minutes, during which nothing is drawn and the app does nothing else (spinning beach ball):

2011-04-27 21:33:00.899 SetNeedsDisplay[80162:a0b] Entered: drawRect:
2011-04-27 21:33:00.901 SetNeedsDisplay[80162:a0b] Image instantiated.
2011-04-27 21:34:57.911 SetNeedsDisplay[80162:a0b] Image drawn.
2011-04-27 21:34:57.912 SetNeedsDisplay[80162:a0b] Bezier path drawn; exiting drawRect.

Requesting iPhone location whilst in background?

5 votes

Simple question ... I have an application that records a users location at 30second intervals (using an NSTimer) it works perfectly until the application goes "inactive" and the NStimer stops. As a consequence I am looking for options to maintain my location interval (30secs) whilst still being able to record fairly accurate location data (within 100m accuracy).

  • Option_001, Brute Force: Let CLLocationManager, startUpdatingLocation run all the time using UIBackgroundModes = "location". Not recommended, drains battery. Regularity upon request, Accuracy approx. 10-65m. Might just be the only realistic option.

  • Option_002, SLC: I could use Significant Location Change but the frequency of location updates is pretty poor (not to mention accuracy). This is particularly true if the application is running in a rural or wilderness area with limited numbers of cell towers. Regularity unknown, Accuracy approx. 500m

  • Option_003, Hybrid: I could use Significant Location Change (SLC) in the background as an indicator of "significant" movement and then request an GPS location based on kCLLocationAccuracyBest. This would work but the SLC events are not going to arrive at anywhere near 30second intervals (particularly when walking). Regularity unknown, Accuracy approx. 10-50m.

  • Option_004, Something else? any ideas would be much appreciated.


NOTE: I thought I had this working because when you press [LOCK] on an iPhone (connected via USB) applicationWillResignActive is called but NSTimers do not stop. If you try the same with the iPhone un-connected (i.e. as the phone would be in normal use) the NSTimers stop almost immediately after applicationWillResignActive is called.

First of all, don't use a timer to update the user location. Approach it from the other end: check, when a new location is received, the interval since the last "recording" and decide if you want to record the new location or now.

Also, this will get around your "inactive" state problem. Just enable background location services. Info.plist > Required background modes > App registers for location updates

Whilst in background, when a new location is received, your app will go in a "background active" state that will allow enough time to make an API call and push the new location.

In a sentence, you need to design this app to work well with the new background modes.

Note: this solution won't work for iOS3.x

Can a category implement a protocol in Objective C?

5 votes

I have a category on NSDate and it would be convenient if it could implement a protocol I previously created. Is this possible? what's the correct syntax for this?

Yes, that's possible. The syntax is:

@interface NSDate (CategoryName) <ProtocolName>
@end

@implementation NSDate (CategoryName)
@end

Here's Apple's documentation on the topic.

What are your naming conventions for Objective-C "private" methods?

5 votes

Inheriting code from other developers has made me a firm believer in keeping as many messages as possible out of a class' public interface by means of a Class Extension. I'm also a firm believer in adopting special naming conventions for private, implementation-specific members of a class. I really like being able to tell at a glance what messages being sent and what members being referenced within the implementation context are not ever intended for public use and vice versa. If nothing else, it makes the overall semantics of a class easier for me grasp more quickly, and that's worth it.

Justification aside, I've written boatloads of classes with boatloads2 of private methods, but I've never really come up with a pattern for naming that I really love (like I do the controversial ivar_ convention for ivars). Notable examples:

@interface myClass()

// I like this, but as we all know, Apple has dibs on this one, 
// and method name collisions are nasty.
- (void)_myPrivateMessage;

// The suffix version promoted by Google for ivars doesn't really translate
// well to method names in Objective-C, because of the way the method
// signature can be broken into several parts.
- (void)doWork_; // That's okay...
- (void)doWork_:(id)work with_:(id)something; // That's just ugly and tedious...
- (void)doWork_:(id)work with_:(id)something and_:(id)another; // My eyes...

// This version is suggested by Apple, and has the benefit of being officially 
// recommended. Alas, I don't like it: The capital letter is ugly. I don't like 
// underscores in the middle of the name. Worst of all, I have to type three characters 
// before code-sense does anything more useful than inform me that I am typing.
- (void)BF_doWork;

@end

At this point, there are a kajillion different means by which I could mangle my private method names, but instead of making something up, I figured I would first take a poll for any popular conventions I may not be aware of. So, what have you used?

I use two levels of private methods: slightly private and very private. Slightly private methods are methods which could become public, but currently aren't. They are usually convenience methods that I use internally, and I usually don't put in as much protection unless I decide to make it public. For very private methods, I ignore apple and use an underscore prefix. Since 99% of my code is in classes I create and I usually have prefixes on my class names, the chances of running into naming problems is small. When adding code to classes I didn't make, I rarely make private methods, but add a short prefix on the rare occasion that I do.