开发者

Cocoa Objective-C adding subviews

I have a game application (cocoa, not cocoa touch) where I am trying to add map elements. My app window is named mainWin. I have a subview of mainWin named viewGameMap, which I added in IB. I have a class called room.h/room.m which basically takes dimensions generated in the app for width and height of the room.

I can do this:

room* thisRoom = [[room alloc] initWithFrame: NSMakeRect(441.0-roomWidth,520.0-roomLength, roomWidth * 10, roomLength * 10)];
[[mainWin contentView] addSubview:thisRoom];

But I really want to add this subview to viewGameMap, can I subview a subview? In IB I noticed that a subview doesn't have a contentView so I'm not sure开发者_运维百科 how I would place it there.

In a related question, these room views wouldn't be permanent so how do I destroy them once I am finished with them.

Thanks


First, if you declare viewGameMap in your .h file, like this (using @property directive):

@property (nonatomic, retain) IBOutlet UIView   *viewGameMap;

or even just in actual declaration, like this:

IBOutlet UIView *viewGameMap;

then you should be able to bind viewGameMap to appropriate UIView within IB. This will give you direct access to viewGameMap.

Second, since you are using alloc to instantiate your Room object (n.b., class Room should be capitalized per convention), you are responsible for it (you own it). But when you call -addSubview:, then [mainWin contentView] also owns thisRoom. So, you can do this:

room* thisRoom = [[room alloc] initWithFrame: NSMakeRect(441.0-roomWidth,520.0-roomLength, roomWidth * 10, roomLength * 10)];
[viewGameMap addSubview:thisRoom];
[thisRoom release];

Later, when thisRoom is removed from [mainWin contentView], its reference count will (barring some other referencing) drop to zero and it will, ultimately, get deallocated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜