-3

I'm trying to get to grips with Objective-C, having programmed in Java and C in the past.

I have a class, Unzip, which contains the following method:

- (void)unzipFile:(NSString*)fileName

I'm trying to call this method from the AppDelegate class, to respond to a button click, using the following code, which creates an instance of Unzip and calls the unzipFile method with a string value, but nothing happens.

- (IBAction)unzipIt:(id)sender {
    NSLog(@"Unzip clicked");
    NSString *zipString = [_testField stringValue];

    NSLog(@"Calling unzip with the string %@", zipString);
    Unzip *unzip;
    [unzip unzipFile:(zipString)]; 
}

The actual button click works, because the two initial NSLogs appear, but nothing further happens. The method is fine as I've tested it elsewhere so at least something should happen. Could anybody please tell me where I'm going wrong?

Thanks for your time.

Mike D
  • 4,938
  • 6
  • 43
  • 99

2 Answers2

3

You didn't allocate Unzip:

Unzip *unzip = [[Unzip alloc] init];
[unzip unzipFile:zipString];

The reason why it is not working, but not blowing up, is in Objective C, it is safe to send a message to nil.

Some more concepts about Objective C, especially in the section Working with Nil.

Thomas Lai
  • 875
  • 4
  • 11
  • 19
Mike D
  • 4,938
  • 6
  • 43
  • 99
0

You have to initialize your unzip variable

Unzip *unzip = [[Unzip alloc] init];

There is also a shortcut:

Unzip *unzip = [Unzip new];

which is equivalent shorthand.

Josh Hudnall
  • 1,021
  • 8
  • 16
  • dont call new, the convention is alloc + init OR a convenience method of your own.. – Daij-Djan Mar 17 '13 at 16:28
  • @Daij-Djan Why is that? – Josh Hudnall Mar 17 '13 at 16:29
  • @JoshHudnall It's preference more than anything. Some people believe that new is the easy way out, and that it may have side-effects. – CodaFi Mar 17 '13 at 16:33
  • http://stackoverflow.com/questions/719877/use-of-alloc-init-instead-of-new-objective-c – Daij-Djan Mar 17 '13 at 16:33
  • @Daij-Djan From my research, it is equivalent to [[alloc] init]. Even Apple use it in certain instances. From what I understand, it is a matter of personal preference. – Josh Hudnall Mar 17 '13 at 16:35
  • I think that new should have never been part of the Lang spec, but I can see why they included it with the whole of NSObject being built on C++. – CodaFi Mar 17 '13 at 16:35
  • Yeah, I saw that answer, but the only even halfway valid reason I can see is that more explicit is better, but I don't feel that to be a true statement in every case. Either way, both work. :) – Josh Hudnall Mar 17 '13 at 16:37