Is it better to autorelease or release right after?

后端 未结 3 677
时光说笑
时光说笑 2020-12-20 15:42

There are a lot of cases in which one would alloc an instance, and release it right after it\'s being assigned to something else, which retains it internally.

For ex

3条回答
  •  太阳男子
    2020-12-20 15:48

    I agree with Matt Ball. Let me just add that, if you find yourself using this pattern frequently, it can be handy to write a quick category:

    @interface UIView (MyCategories)
    - (UIView *)addNewSubviewOfType:(Class)viewType inFrame:(NSRect)frame;
    @end
    
    @implementation UIView (MyCategories)
    - (UIView *)addNewSubviewOfType:(Class)viewType inFrame:(NSRect)frame
    {
        UIView * newView = [[viewType alloc] initWithFrame:frame];
        [self addSubView:newView];
        return [newView autorelease];
    }
    @end
    

    Which can be used as follows:

    UIView * view = [someView addNewSubviewOfType:[UIView class]
                                          inFrame:someFrame];
    

    And it even works with other types, as long as they are derived from UIView:

    UIButton * button = [mainView addNewSubviewOfType:[UIButton class]
                                              inFrame:buttonFrame];
    

提交回复
热议问题