Oh! Apple

My experience of using iPod Touch, iPod Classics, Mac OSX, Coding in XCode, or anything generally related to Apple

Monday, April 28, 2008

Another Objective C question.


------------
I am pretty new to Objective C, and instead code C# as day job.  iPhone SDK brought me to the Mac coding world.

Even though my ultimate goal is to write an iPhone application, I want to write my code in TDD (Test Driven Deployment) approach.  Because OCUnit doesn't seem to work too well with iPhone SDK beta 3 (I wonder if I have better luck with beta 4 which released today and I already installed it), so I created a regular Cocca application, and then use OCUnit with it.  My goal is to put all my logic in domain objects, have them all fully tested by OCUnit unit tests.  And then eventually use all the objects in the iPhone app.  In fact, I think this approach matches the philosophy  of MVC design pattern, which the domain model objects should be decoupled from the UI (view) and controller (plumping or glue).  Am I on the right track?

So I wrote my unit tests, and one of them looks like this:

- (void) testChordWithInvalidChordName_ShouldNot_BeInstantiated
{
NSString* chordNameToTest;
DeecayChord* newChordToTest;
BOOL isExceptionThrow;

@try
{
chordNameToTest = @"SS";
newChordToTest = [[DeecayChord alloc] initWith: chordNameToTest];


isExceptionThrow = NO;
}
@catch (NSException *e)
{
isExceptionThrow = YES;
}

STAssertTrue(isExceptionThrow, nil);

//[chordNameToTest release];
//[newChordToTest release];

@try
{
chordNameToTest = @"Eb";
newChordToTest = [[DeecayChord alloc] initWith: chordNameToTest];

isExceptionThrow = NO;
}
@catch (NSException *e)
{
isExceptionThrow = YES;
}

STAssertFalse(isExceptionThrow, nil);

[chordNameToTest release];
[newChordToTest release];
}

The code ran OK.  You might notice that I remarked out the two release statement in the middle.  If I unremarked then the code will failed, which got me slightly puzzled.  Maybe I don't quit understand how alloc and init works.  Here's my logic: when alloc got called, some new memory space was set aside for the object I instantiate, and that's why I need to release the memory I occupied at the end.  But since the DeecayChord object got allocated twice for two different objects, I probably need to release each instance once, and thus calls release twice. But instead the code didn't compile if I do so.

Obvious some assumptions I made was wrong, but should someone point out my logic flaw?

Thanks!



0 Comments:

Post a Comment

<< Home