gpt4 book ai didi

objective-c - Objective-C 分布式对象的内存管理 : my temporary instances live forever!

转载 作者:行者123 更新时间:2023-12-03 17:26:57 26 4
gpt4 key购买 nike

我正在玩 Objective-C Distributed Objects我在理解系统下内存管理的工作原理时遇到一些问题。下面给出的示例说明了我的问题:

协议(protocol).h

#import <Foundation/Foundation.h>

@protocol DOServer
- (byref id)createTarget;
@end

Server.m

#import <Foundation/Foundation.h>
#import "Protocol.h"


@interface DOTarget : NSObject
@end


@interface DOServer : NSObject < DOServer >
@end


@implementation DOTarget

- (id)init
{
if ((self = [super init]))
{
NSLog(@"Target created");
}
return self;
}

- (void)dealloc
{
NSLog(@"Target destroyed");
[super dealloc];
}

@end

@implementation DOServer

- (byref id)createTarget
{
return [[[DOTarget alloc] init] autorelease];
}

@end


int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

DOServer *server = [[DOServer alloc] init];

NSConnection *connection = [[NSConnection new] autorelease];
[connection setRootObject:server];
if ([connection registerName:@"test-server"] == NO)
{
NSLog(@"Failed to vend server object");
}
else
{
while (YES)
{
NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init];
[[NSRunLoop currentRunLoop] runUntilDate:
[NSDate dateWithTimeIntervalSinceNow:0.1f]];
[innerPool drain];
}
}

[pool drain];
return 0;
}

Client.m

#import <Foundation/Foundation.h>
#import "Protocol.h"

int main()
{
unsigned i = 0;
for (; i < 3; i ++)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
id server = [NSConnection rootProxyForConnectionWithRegisteredName:@"test-server"
host:nil];
[server setProtocolForProxy:@protocol(DOServer)];
NSLog(@"Created target: %@", [server createTarget]);

[[NSRunLoop currentRunLoop] runUntilDate:
[NSDate dateWithTimeIntervalSinceNow:1.0]];
[pool drain];
}
return 0;
}

问题是,当客户端中的代理对应对象超出范围时,根代理创建的任何远程对象都不会被释放。根据the documentation :

When an object’s remote proxy is deallocated, a message is sent back to the receiver to notify it that the local object is no longer shared over the connection.

因此,我希望当每个 DOTarget 超出范围(每次循环时)时,它的远程对应项都会被释放,因为远程端没有其他对它的引用连接的。

实际上,这种情况不会发生:临时对象仅在客户端应用程序退出时,或更准确地说,在连接失效时才被释放。我可以通过显式地使每次循环时使用的 NSConnection 对象无效并创建一个新对象来强制释放远程端的临时对象,但不知怎的,这感觉是错误的。

这是 DO 的正确行为吗?所有临时对象是否都应该与创建它们的连接一样长久存在?因此,连接是否应被视为临时对象,应在针对服务器的每一系列请求中打开和关闭?

任何见解将不胜感激。

最佳答案

服务器上的自动释放池永远不会耗尽,因此自动释放的对象永远不会“超出范围”。您将始终对它们有额外的引用。设置您的服务器类似于您在客户端中设置的测试(每秒左右转储一次运行循环),并每次耗尽并建立一个新的内部池。然后您将看到预期的结果。

关于objective-c - Objective-C 分布式对象的内存管理 : my temporary instances live forever!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2521514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com