Can I pass delegate as a parameter objective-c

Slee picture Slee · Jun 13, 2012 · Viewed 8.8k times · Source

I am working with an NSOperationQueue and I want to add new NSOperations to the NSOperationQueue. It is a queue that lives in a singleton instance of a class I have. It would make things a lot easier if I could move everything into the static class by passing the delegate.

Here is my code now as it lives in - this is in a cellForRowAtIndexPath

 NSString *key = [NSString stringWithFormat:@"%@%@",cell.dataItem.ItemID, cell.dataItem.ManufacturerID];

        if (![self.imgOperationInQueue valueForKey:key]) {

            ImageOperation *imgOp = [[ImageOperation alloc] initWithItemID:cell.dataItem.ItemID withManufacturerID:cell.dataItem.ManufacturerID withReurnType:kThumbnail];
            imgOp.identifier = [NSString stringWithFormat:@"%i", cell.tag];
            imgOp.delegate = self;
            [[SharedFunctions sharedInstance] addImageOperationToQueue:imgOp];
            [imgOp release];

            // store these in the dictionary so we don;t queue up requests more than once
            [self.imgOperationInQueue setValue:cell.dataItem.ItemID forKey:key];
        }

If I could add the delegate as a parameter I could put all of this code into the shared singleton class and call it from anywhere in my app.

I suppose that I could use an NSNotification - or can I use a block of some sort?

Answer

bbarnhart picture bbarnhart · Jun 13, 2012

Just create the appropriate init method that passes in the delegate.

- (id)initWithItemID:(NSString *)itemID
  withManufacturerID:(NSString *)manufacturerID
       withReurnType:(NSInteger)type
            delegate:(id<YourDelegate>)theDelegate
{
    self = [super init];
    if (self)
    {
        .... // Other assignments
        self.delegate = theDelegate;
    }

    return self;
}