首页 \ 问答 \ NSMutableArray线程安全(NSMutableArray thread safety)

NSMutableArray线程安全(NSMutableArray thread safety)

在我的应用程序中,我正在从多个线程访问和更改可变数组。 在开始时,当我尝试访问objectAtIndex对象时发生崩溃,因为索引超出了范围(该索引处的对象已经从另一个线程中的数组中移除)。 我在互联网上搜索如何解决这个问题,我决定尝试这个解决方案 。我做了一个NSMutableArray属性的类,请参阅以下代码:

@interface SynchronizedArray()
@property (retain, atomic) NSMutableArray *array;
@end

@implementation SynchronizedArray

- (id)init
{
    self = [super init];
    if (self)
    {
        _array = [[NSMutableArray alloc] init];
    }
    return self;
}

-(id)objectAtIndex:(NSUInteger)index
{
    @synchronized(_array)
    {
        return [_array objectAtIndex:index];
    }
}

-(void)removeObject:(id)object
{
    @synchronized(_array)
    {
        [_array removeObject:object];
    }
}

-(void)removeObjectAtIndex:(NSUInteger)index
{
    @synchronized(_array)
    {
        [_array removeObjectAtIndex:index];
    }
}

-(void)addObject:(id)object
{
    @synchronized(_array)
    {
        [_array addObject:object];
    }
}

- (NSUInteger)count
{
    @synchronized(_array)
    {
        return [_array count];
    }
}

-(void)removeAllObjects
{
    @synchronized(_array)
    {
        [_array removeAllObjects];
    }
}

-(id)copy
{
    @synchronized(_array)
    {
        return [_array copy];
    }
}

我使用这个类而不是旧的可变数组,但该应用程序仍在这条线上崩溃: return [_array objectAtIndex:index]; 我也试过这种方法与NSLock ,但没有运气。 我做错了什么以及如何解决这个问题?


In my app I'm accessing and changing a mutable array from multiple threads. At the beginning it was crashing when I was trying to access an object with objectAtIndex, because index was out of bounds (object at that index has already been removed from array in another thread). I searched on the internet how to solve this problem, and I decided to try this solution .I made a class with NSMutableArray property, see the following code:

@interface SynchronizedArray()
@property (retain, atomic) NSMutableArray *array;
@end

@implementation SynchronizedArray

- (id)init
{
    self = [super init];
    if (self)
    {
        _array = [[NSMutableArray alloc] init];
    }
    return self;
}

-(id)objectAtIndex:(NSUInteger)index
{
    @synchronized(_array)
    {
        return [_array objectAtIndex:index];
    }
}

-(void)removeObject:(id)object
{
    @synchronized(_array)
    {
        [_array removeObject:object];
    }
}

-(void)removeObjectAtIndex:(NSUInteger)index
{
    @synchronized(_array)
    {
        [_array removeObjectAtIndex:index];
    }
}

-(void)addObject:(id)object
{
    @synchronized(_array)
    {
        [_array addObject:object];
    }
}

- (NSUInteger)count
{
    @synchronized(_array)
    {
        return [_array count];
    }
}

-(void)removeAllObjects
{
    @synchronized(_array)
    {
        [_array removeAllObjects];
    }
}

-(id)copy
{
    @synchronized(_array)
    {
        return [_array copy];
    }
}

and I use this class instead of old mutable array, but the app is still crashing at this line: return [_array objectAtIndex:index]; I tried also this approach with NSLock, but without a luck. What I'm doing wrong and how to fix this?


原文:https://stackoverflow.com/questions/21139581
更新时间:2023-10-07 19:10

最满意答案

你已经快到了。 大概。

您正在使用正确的方法来检索注释,因此您可以使用值。

您的问题 - 如果我解释非常简约的问题描述 (!),您只通过代码片段(!)中的注释正确提供 - 是(错误的)假设将类型Class的数组粘贴到System.out.println中( )将打印出它包含的类的名称。 它不是。 而是打印有关参考的信息:

[Ljava.lang.Class;@15db9742

如果需要类的名称,则必须遍历该数组的元素并使用.getName(),. getSimpleName()或提供Class方法的其他名称之一。

有关如何打印数组元素的更多信息,请访问:

打印Java数组最简单的方法是什么?

当然,如果问题在于您从注释字段中获取空值,那么整个答案可能完全不同于这一点。 但是,由于您没有提供足够的问题描述(“ 无效不是问题描述! ),我们只能猜测您的问题是什么。


The solution for this is making sure the advice method's parameter name match the parameter name in AspectJ expression. In my case, the advice method should look like this:

@Aspect
public class MyAspect {
    @Around("@annotation(myAnnotation)")
    public Object handle(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) {
        System.out.println(myAnnotation.exceptionList); // should print out TimeOutException
    }
}

相关问答

更多
  • 浪费了更多时间之后,我发现我已经将两种不同的AspectJ sytnax混合在一起。 一个是关于方面(比如“公共方面LoggingAspect”),另一个是常规Java注释(比如“@Aspect”或“@Around”)。 当我用“public class LoggingAspect”替换了“公共方面的LoggingAspect”时,它就起作用了。 很难发现,因为一切仍然没有问题编译。 希望有朝一日能够帮助某人,或者至少在将来的ajc版本中,他们会添加更详细的编译器输出。 After wasting even ...
  • 不确定您正在阅读哪些文档 - https://eclipse.org/aspectj/doc/next/adk15notebook/ataspectj-pcadvice.html上的页面向您展示了如何从代码转换为注释样式。 我承认他们并不像他们那样全面。 基本上: 从aspect关键字切换到@Aspect 将切入点移动到方法上指定的字符串@Pointcut注释中 将您的建议从未命名的块转换为方法。 (由于要继续的参数,这对于周围的建议可能会变得棘手) 你的原创成为: @Aspect public class ...
  • 尝试这个: @Around("execution (* *(fully.qualified.name.CloudFile)) && args(cloudFile)") public Object captureFileAttribute(ProceedingJoinPoint joinPoint, CloudFile cloudFile) throws Throwable { Object result = joinPoint.proceed(); System.err.pr ...
  • 目前,AspectJ支持对允许类型的注释值的子集进行注释值匹配。 不幸的是,不支持您使用的数组类型(也不支持类)。 1.6.0 AspectJ README( https://eclipse.org/aspectj/doc/released/README-160.html )中记录了此功能。 有一个关于'注释值匹配'的部分。 如上所述,语法实际上对于基本情况非常直观: enum TraceLevel { NONE, LEVEL1, LEVEL2, LEVEL3 } @interface Trace { ...
  • before()和after()建议不能修改在连接点发生的事情,他们只能观察它。 around()建议会做你需要的。 就像是: void around(long l,boolean b): execution(* delete(..)) && args(l,b) { if ((l%2)==0) { proceed(l,b); } else { proceed(l,!b); } } 对不起,我用代码风格写了它,我对此更熟悉。 这可以使用注释样式,但您需要使用其他变量Proceed ...
  • 你已经快到了。 大概。 您正在使用正确的方法来检索注释,因此您可以使用值。 您的问题 - 如果我解释非常简约的问题描述 (!),您只通过代码片段(!)中的注释正确提供 - 是(错误的)假设将类型Class的数组粘贴到System.out.println中( )将打印出它包含的类的名称。 它不是。 而是打印有关参考的信息: [Ljava.lang.Class;@15db9742 如果需要类的名称,则必须遍历该数组的元素并使用.getName(),. getSimpleName()或提供Class方法的其他名 ...
  • 尝试添加以启用加载时间编织,并将spring-aspects.jar添加到类路径中。 有关详细信息,请参阅http://static.springsource.org/spring/docs/current/spring-framework-reference/html/aop.html#aop-aj-ltw-spring 编辑 对于通用Java应用程序,即不在Web或应用程序容器中运行,您需要通过javaagent选项启用java instrument ...
  • 我是AspectJ项目的负责人。 在https://bugs.eclipse.org/bugs/show_bug.cgi?id=313026下,我们正在研究如何使用declare annotation: 扩充现有注释(将值添加到已存在的注释中) 替换他们 定义优先级(如果你声明替换那里有什么?) 我们还在寻找一种删除注释的形式: 声明@remove_from_method:int mymethod():@ ToBeRemoved; 但你还不能做到...... I'm the AspectJ project ...
  • 我已经编写了一个关于事务管理评论的MCVE示例,以便使代码及其日志输出更加清晰: 注解: package de.scrum_master.app; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(Retentio ...
  • 使用declare precedence来定义所需的宽高优先顺序。 有关此优先级和默认优先级的更多信息,请参阅“AspectJ编程指南”的“ 语言语义 ”一节。 如果建议顺序应该是动态的,那么最好的办法是让一个切入点同时捕获注释并根据注释的值来决定顺序,这些值可以通过反射来确定。 Use declare precedence in order to define your desired order of aspect precedence. Further information about this a ...

相关文章

更多

最新问答

更多
  • 如何在Laravel 5.2中使用paginate与关系?(How to use paginate with relationships in Laravel 5.2?)
  • linux的常用命令干什么用的
  • 由于有四个新控制器,Auth刀片是否有任何变化?(Are there any changes in Auth blades due to four new controllers?)
  • 如何交换返回集中的行?(How to swap rows in a return set?)
  • 在ios 7中的UITableView部分周围绘制边界线(draw borderline around UITableView section in ios 7)
  • 使用Boost.Spirit Qi和Lex时的空白队长(Whitespace skipper when using Boost.Spirit Qi and Lex)
  • Java中的不可变类(Immutable class in Java)
  • WordPress发布查询(WordPress post query)
  • 如何在关系数据库中存储与IPv6兼容的地址(How to store IPv6-compatible address in a relational database)
  • 是否可以检查对象值的条件并返回密钥?(Is it possible to check the condition of a value of an object and JUST return the key?)
  • GEP分段错误LLVM C ++ API(GEP segmentation fault LLVM C++ API)
  • 绑定属性设置器未被调用(Bound Property Setter not getting Called)
  • linux ubuntu14.04版没有那个文件或目录
  • 如何使用JSF EL表达式在param中迭代变量(How to iterate over variable in param using JSF EL expression)
  • 是否有可能在WPF中的一个单独的进程中隔离一些控件?(Is it possible to isolate some controls in a separate process in WPF?)
  • 使用Python 2.7的MSI安装的默认安装目录是什么?(What is the default installation directory with an MSI install of Python 2.7?)
  • 寻求多次出现的表达式(Seeking for more than one occurrence of an expression)
  • ckeditor config.protectedSource不适用于editor.insertHtml上的html元素属性(ckeditor config.protectedSource dont work for html element attributes on editor.insertHtml)
  • linux只知道文件名,不知道在哪个目录,怎么找到文件所在目录
  • Actionscript:检查字符串是否包含域或子域(Actionscript: check if string contains domain or subdomain)
  • 将CouchDB与AJAX一起使用是否安全?(Is it safe to use CouchDB with AJAX?)
  • 懒惰地初始化AutoMapper(Lazily initializing AutoMapper)
  • 使用hasclass为多个div与一个按钮问题(using hasclass for multiple divs with one button Problems)
  • Windows Phone 7:检查资源是否存在(Windows Phone 7: Check If Resource Exists)
  • 无法在新线程中从FREContext调用getActivity()?(Can't call getActivity() from FREContext in a new thread?)
  • 在Alpine上升级到postgres96(/ usr / bin / pg_dump:没有这样的文件或目录)(Upgrade to postgres96 on Alpine (/usr/bin/pg_dump: No such file or directory))
  • 如何按部门显示报告(How to display a report by Department wise)
  • Facebook墙贴在需要访问令牌密钥后无法正常工作(Facebook wall post not working after access token key required)
  • Javascript - 如何在不擦除输入的情况下更改标签的innerText(Javascript - how to change innerText of label while not wiping out the input)
  • WooCommerce / WordPress - 不显示具有特定标题的产品(WooCommerce/WordPress - Products with specific titles are not displayed)