为什么我的程序在使用 self.property 访问属性时会崩溃?和一个合成的访问器?

问题描述 投票:0回答:4

我有数据对象类:

@interface Item: NSObject {
    NSString *title;
    NSString *text;
}

@property (copy) NSString *title;
@property (copy) NSString *text;

@end

@implementation Item

@synthesize text;

- (void)updateText {
    self.text=@"new text";
}

- (NSString *)title {
    return title;
}

- (void)setTitle:(NSString *)aString {
    [title release];
    title = [aString copy];
}

@end

在使用非合成方法时,我可以很好地设置

title
属性,但是当我使用合成访问器设置属性时,我在
updateText
方法中收到错误,内容如下:

self.text=@"new text";

错误是:

*** NSInvocation: warning: object 0x462d2c0 of class '_NSZombie_CFString' does not implement methodSignatureForSelector: -- trouble ahead
*** NSInvocation: warning: object 0x462d2c0 of class '_NSZombie_CFString' does not implement doesNotRecognizeSelector: -- abort

为什么相同的非综合访问器可以工作而综合访问器却不能?

该对象是在主线程中创建的,从 NSOperation 线程访问该对象时会出现错误。

objective-c cocoa memory zombie-process
4个回答
3
投票

setter 应该这样编码:

[title autorelease]
title = [aString copy];

否则另一个线程可能会得到在其脚下释放的标题对象。

或者从 Cocoa 内存管理编程指南

中选择任何其他一致的访问器样式

0
投票

您发布的代码对我来说效果很好。此代码与您使用的实际代码有什么不同吗?

您看到的错误消息引用了“僵尸”,它们是指向已释放对象的指针。这段代码中没有任何内容显示出此类行为的任何风险,这让我认为实际的错误在其他地方。

一种可能的解决方案是使用 Xcode 的调试器来查看

NSString
对象的地址,并使用该信息来确定哪个对象最终会导致
NSInvocation
警告。


0
投票

在此代码中,

[self setTitle:[self title]]
将在复制之前释放并释放
title
。 您需要检查 setter 中是否有
title == aString


0
投票
#Second option

import numpy as np
from scipy.stats import norm
import math

class DerivativePricer:
    """Base class for derivative pricing."""
    def __init__(self, S0, K, T, R, sigma):
        self.S0 = S0      # Initial stock price
        self.K = K        # Strike price
        self.T = T        # Time to maturity
        self.R = R        # Risk-free interest rate
        self.sigma = sigma# Volatility of the stock

    def price(self):
        """Method to compute the price of the derivative."""
        raise NotImplementedError("Method 'price' not implemented.")

class AnalyticPricer(DerivativePricer):
    """Analytic solution for the pricing under Black-Scholes model."""
    def price(self):
        """Use the analytic formula for a squared payoff under BS model."""
        d1 = (math.log(self.S0 / self.K) + (self.R + 0.5 * self.sigma**2) * self.T) / (self.sigma * math.sqrt(self.T))
        d2 = d1 - self.sigma * math.sqrt(self.T)
        
        # Components of the expectation calculation
        first_term = self.S0**2 * np.exp(2 * (self.R + self.sigma**2) * self.T) * norm.cdf(d1 + self.sigma * math.sqrt(self.T))
        second_term = -2 * self.K * self.S0 * np.exp(self.R * self.T) * norm.cdf(d1)
        third_term = self.K**2 * norm.cdf(d2)
        
        return np.exp(-self.R * self.T) * (first_term + second_term + third_term)

class MonteCarloPricer(DerivativePricer):
    """Monte Carlo simulation for the pricing under Black-Scholes model."""
    def __init__(self, S0, K, T, R, sigma, num_simulations=10000):
        super().__init__(S0, K, T, R, sigma)
        self.num_simulations = num_simulations
    
    def price(self):
        """Simulate the payoff and calculate the discounted average."""
        dt = self.T
        drift = (self.R - 0.5 * self.sigma**2) * dt
        diffusion = self.sigma * math.sqrt(dt)
        payoffs = []
        
        for _ in range(self.num_simulations):
            Z = np.random.normal()
            ST = self.S0 * np.exp(drift + diffusion * Z)
            payoff = (ST - self.K)**2
            payoffs.append(payoff)
        
        mean_payoff = np.mean(payoffs)
        present_value = np.exp(-self.R * self.T) * mean_payoff
        return present_value

# Parameters
S0 = 59.72
K = 59.72
T = 0.25
R = 0.0419
sigma = 0.0732

# Pricers
analytic_pricer = AnalyticPricer(S0, K, T, R, sigma)
mc_pricer = MonteCarloPricer(S0, K, T, R, sigma)

# Pricing
analytic_price = analytic_pricer.price()
mc_price = mc_pricer.price()

print(f"Analytic Price: {analytic_price}")
print(f"Monte Carlo Price: {mc_price}")
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.