Transitioning to ARC Release Notes

097634e9169c6777120550ad61afb6bc-1.jpg 立即下载
 

Automatic Reference Counting (ARC) is a compiler feature that provides automatic memory management of Objective-C objects. Rather than having to think about about retain and release operations, ARC allows you to concentrate on the interesting code, the object graphs, and the relationships between objects in your application.

image: Art/ARC_Illustration.jpg image: Art/ARC_Illustration.jpg
Contents:

Summary
ARC Overview
Managing Toll-Free Bridging
Common Issues While Converting a Project
Frequently Asked Questions


Summary

ARC works by adding code at compile time to ensure that objects live as long as necessary, but no longer. Conceptually, it follows the same memory management conventions as manual reference counting (described in Advanced Memory Management Programming Guide), by adding the appropriate retain, release, and autorelease method calls for you.

In order for the compiler to generate correct code, ARC restricts the methods you can use and how you use toll-free bridging (see “Toll-Free Bridged Types”). ARC also introduces new lifetime qualifiers for object references and declared properties.

ARC is supported in Xcode 4.2 for Mac OS X v10.6 and v10.7 (64-bit applications) and for iOS 4 and iOS 5. Weak references are not supported in Mac OS X v10.6 and iOS 4.

Xcode has a new tool that automates the mechanical parts of the ARC conversion (such as removing retain and release calls) and helps you to fix issues the migrator can’t handle automatically. The migration tool converts all files in a project to use ARC. You can also choose to use ARC on a per-file basis if it’s more convenient for you to use manual reference counting for some files.

See also:

ARC Overview

Instead of you having to remember when to use retain, release, and autorelease, ARC evaluates the lifetime requirements of your objects and automatically inserts the appropriate method calls for you at compile time. The compiler also generates appropriate dealloc methods for you. In general, if you’re only using ARC the traditional Cocoa naming conventions are important only if you need to interoperate with code that uses manual reference counting.

A complete and correct implementation of a Person class might look like this:

@interface Person : NSObject
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSNumber *yearOfBirth;
@property (nonatomic, strong) Person *spouse;
@end
 
@implementation Person
@synthesize firstName, lastName, yearOfBirth, spouse;
@end

(The strong attribute is described in “ARC Introduces New Lifetime Qualifiers”.)

Using ARC, you could implement a contrived method like this:

- (void)contrived {
    Person *aPerson = [[Person alloc] init];
    [aPerson setFirstName:@"William"];
    [aPerson setLastName:@"Dudney"];
    [aPerson:setYearOfBirth:[[NSNumber alloc] initWithInteger:2011]];
    NSLog(@"aPerson: %@", aPerson);
}

ARC takes care of memory management so that neither the Person nor the NSNumber objects are leaked.

You could also safely implement a takeLastNameFrom: method of Person like this:

- (void)takeLastNameFrom:(Person *)person {
    NSString *oldLastname = [self lastName];
    [self setLastName:[person lastName]];
    NSLog(@"Lastname changed from %@ to %@", oldLastname, [self lastName]);
}

ARC ensures that oldLastName is not deallocated before the NSLog statement.

ARC Enforces New Rules

To work, ARC imposes some new rules that are not present when using other compiler modes. The rules are intended to provide a fully reliable memory management model; in some cases, they simply enforce best practice, in some others they simplify your code or are obvious corollaries of your not having to deal with memory management. If you violate these rules, you get an immediate compile-time error, not a subtle bug that may become apparent at runtime.

  • You cannot explicitly invoke dealloc, or implement or invoke retain, release, retainCount, or autorelease.

    The prohibition extends to using @selector(retain), @selector(release), and so on.

    You may implement a dealloc method if you need to manage resources other than releasing instance variables. You do not have to (indeed you cannot) release instance variables, but you may need to invoke [systemClassInstance setDelegate:nil] on system classes and other code that isn’t compiled using ARC.

    Custom dealloc methods in ARC do not require a call to [super dealloc] (it actually results in a compiler error). The chaining to super is automated and enforced by the compiler.

    You can still use CFRetain, CFRelease, and other related functions with Core Foundation-style objects (see “Managing Toll-Free Bridging”).

  • You cannot use NSAllocateObject or NSDeallocateObject.

    You create objects using alloc; the runtime takes care of deallocating objects.

  • You cannot use object pointers in C structures.

    Rather than using a struct, you can create an Objective-C class to manage the data instead.

  • There is no casual casting between id and void *.

    You must use special casts that tell the compiler about object lifetime. You need to do this to cast between Objective-C objects and Core Foundation types that you pass as function arguments. For more details, see “Managing Toll-Free Bridging”.

  • Cannot use NSAutoreleasePool objects.

    ARC provides @autoreleasepool blocks instead. These have an advantage of being more efficient than NSAutoreleasePool.

  • You cannot use memory zones.

    There is no need to use NSZone any more—they are ignored by the modern Objective-C runtime anyway.

To allow interoperation with manual retain-release code, ARC imposes some constraints on method and variable naming:

  • You cannot give a property a name that begins with new.

ARC Introduces New Lifetime Qualifiers

ARC introduces several new lifetime qualifiers for objects, and zeroing weak references. A weak reference does not extend the lifetime of the object it points to. A zeroing weak reference automatically becomes nil if the object it points to is deallocated.

You should take advantage of these qualifiers to manage the object graphs in your program. In particular, ARC does not guard against strong reference cycles (previously known as retain cycles—see “Practical Memory Management”). Judicious use of weak relationships will help to ensure you don’t create cycles.

Property Attributes

The keywords weak and strong are introduced as new declared property attributes, as shown in the following examples.

// The following declaration is a synonym for: @property(retain) MyClass *myObject;
@property(strong) MyClass *myObject;
 
// The following declaration is similar to "@property(assign) MyClass *myObject;"
// except that if the MyClass instance is deallocated,
// the property value is set to nil instead of remaining as a dangling pointer.
@property(weak) MyClass *myObject;
Variable Qualifiers

You use the following lifetime qualifiers for variables just like you would, say, const.

__strong
__weak
__unsafe_unretained
__autoreleasing

__strong is the default. __weak specifies a zeroing weak reference to an object. __unsafe_unretained specifies weak reference to an object that is not zeroing—if the object it references is deallocated, the pointer is left dangling. You use __autoreleasing to denote arguments that are passed by reference (id *) and are autoreleased on return.

Take care when using __weak variables on the stack. Consider the following example:

NSString __weak *string = [[NSString alloc] initWithFormat:@"First Name: %@", [self firstName]];
NSLog(@"string: %@", string);

Although string is used after the initial assignment, there is no other strong reference to the string object at the time of assignment; it is therefore immediately deallocated. The log statement shows that string has a null value.

You also need to take care with objects passed by reference. The following code will work:

NSError *error = nil;
BOOL OK = [myObject performOperationWithError:&error];
if (!OK) {
    // Report the error.
    // ...

However, the error declaration is implicitly:

NSError * __strong e = nil;

and the method declaration would typically be:

-(BOOL)performOperationWithError:(NSError * __autoreleasing *)error;

The compiler therefore rewrites the code:

NSError __strong *error = nil;
NSError __autoreleasing *tmp = error;
BOOL OK = [myObject performOperationWithError:&tmp];
error = tmp;
if (!OK) {
    // Report the error.
    // ...

The mismatch between the local variable declaration (__strong) and the parameter (__autoreleasing) causes the compiler to create the temporary variable. You can get the original pointer by declaring the parameter id __strong * when you take the address of a __strong variable. Alternatively you can declare the variable as __autoreleasing.

Use Lifetime Qualifiers to Avoid Strong Reference Cycles

You can use lifetime qualifiers to avoid strong reference cycles. For example, typically if you have a graph of objects arranged in a parent-child hierarchy and parents need to refer to their children and vice versa, then you make the parent-to-child relationship strong and the child-to-parent relationship weak. Other situations may be more subtle, particularly when they involve block objects.

In manual reference counting mode, __block id x; has the effect of not retaining x. In ARC mode, __block id x; defaults to retaining x (just like all other values). To get the manual reference counting mode behavior under ARC, you could use __unsafe_unretained __block id x;. As the name __unsafe_unretained implies, however, having a non-retained variable is dangerous (because it can dangle) and is therefore discouraged. Two better options are to either use __weak (if you don’t need to support iOS 4 or OS X v10.6), or set the __block value to nil to break the retain cycle.

The following code fragment illustrates this issue using a pattern that is sometimes used in manual reference counting.

MyViewController *myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler =  ^(NSInteger result) {
   [myController dismissViewControllerAnimated:YES completion:nil];
};
[self presentViewController:myController animated:YES completion:^{
   [myController release];
}];

As described, instead, you can use a __block qualifier and set the myController variable to nil in the completion handler:

__block MyViewController *myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler =  ^(NSInteger result) {
    [myController dismissViewControllerAnimated:YES completion:nil];
    myController = nil;
};

Alternatively, you can use a temporary __weak variable. The following example illustrates a simple implementation:

MyViewController *myController = [[MyViewController alloc] init…];
// ...
__weak MyViewController *weakMyViewController = myController;
myController.completionHandler =  ^(NSInteger result) {
    [weakMyViewController dismissViewControllerAnimated:YES completion:nil];
};

For non-trivial cycles, however, you should use:

MyViewController *myController = [[MyViewController alloc] init…];
// ...
__weak MyViewController *weakMyController = myController;
myController.completionHandler =  ^(NSInteger result) {
    MyViewController *strongMyController = weakMyController;
    if (strongMyController) {
        // ...
        [strongMyController dismissViewControllerAnimated:YES completion:nil];
        // ...
    }
    else {
        // Probably nothing...
    }
};

In some cases you can use __unsafe_unretained if the class isn’t __weak compatible. This can, however, become impractical for nontrivial cycles because it can be hard or impossible to validate that the __unsafe_unretained pointer is still valid and still points to the same object in question.

ARC Provides a New Statement to Manage Autorelease Pools

Using ARC, you cannot manage autorelease pools directly using the NSAutoReleasePool class. Instead, ARC introduces a statement construct to the Objective-C grammar:

@autoreleasepool {
     // Code, such as a loop that creates a large number of temporary objects.
}

This simple structure allows the compiler to reason about the reference count state.

On entry, an autorelease pool is pushed. On normal exit (break, return, goto, fall-through, and so on) the autorelease pool is popped. For compatibility with existing code, if exit is due to an exception, the autorelease pool is not popped.

This syntax is available in all Objective-C modes. It is more efficient than using the NSAutoReleasePool class; you are therefore encouraged to adopt it in place of using the NSAutoReleasePool.

Patterns for Managing Outlets Become Consistent Across Platforms

The patterns for declaring outlets in iOS and OS X change with ARC and become consistent across both platforms. The pattern you should typically adopt is: outlets should be weak, except for those from File’s Owner to top-level objects in a nib file (or a storyboard scene) which should be strong.

Full details are given in “Nib Files” in Resource Programming Guide.

Stack Variables Are Initialized with nil

Using ARC, strong, weak, and autoreleasing stack variables are now implicitly initialized with nil. For example:

- (void)myMethod {
    NSString *name;
    NSLog(@"name: %@", name);
}

will log null for the value of name rather than perhaps crashing.

Use Compiler Flags to Enable and Disable ARC

You enable ARC using a new -fobjc-arc compiler flag. You can also choose to use ARC on a per-file basis if it’s more convenient for you to use manual reference counting for some files. For projects that employ ARC as the default approach, you can disable ARC for a specific file using a new -fno-objc-arc compiler flag for that file.

ARC is supported in Xcode 4.2 for Mac OS X v10.6 and v10.7 (64-bit applications) and for iOS 4 and iOS 5. Weak references are not supported in Mac OS X v10.6 and iOS 4. There is no ARC support in Xcode 4.1 and earlier.

Managing Toll-Free Bridging

In many Cocoa applications, you need to use Core Foundation-style objects, whether from the Core Foundation framework itself (such as CFArrayRef or CFMutableDictionaryRef) or from frameworks that adopt Core Foundation conventions such as Core Graphics (you might use types like CGColorSpaceRef and CGGradientRef).

The compiler does not automatically manage the lifetimes of Core Foundation objects; you must call CFRetain and CFRelease (or the corresponding type-specific variants) as dictated by the Core Foundation memory management rules (see Memory Management Programming Guide for Core Foundation).

If you cast between Objective-C and Core Foundation-style objects, you need to tell the compiler about the ownership semantics of the object using either a cast (defined in objc/runtime.h) or a Core Foundation-style macro (defined in NSObject.h):

  1. If you prefer the appearance of function calls, you can use macros like CFBridgingRetain. The macros use new modifiers to cast between id and void* to tell the compiler about the retain count effect on the void*.

    NS_INLINE CFTypeRef CFBridgingRetain(id X) {
        return (__bridge_retain CFTypeRef)X;
    }
     
    NS_INLINE id CFBridgingRelease(CFTypeRef X) {
        return (__bridge_transfer id)X;
    }

    A no-op conversion still requires (__bridge).

  2. If you prefer “C-like” casts, you can use the casts directly:

    id my_id;
    CFStringRef my_cfref;
    ...
    NSString   *a = (__bridge NSString*)my_cfref;     // Noop cast.
    CFStringRef b = (__bridge CFStringRef)my_id;      // Noop cast.
    ...
    NSString   *c = (__bridge_transfer NSString*)my_cfref; // -1 on the CFRef
    CFStringRef d = (__bridge_retained CFStringRef)my_id;  // returned CFRef is +1

The Compiler Handles CF Objects Returned From Cocoa Methods

The compiler understands Objective-C methods that return Core Foundation types follow the historical Cocoa naming conventions (see Advanced Memory Management Programming Guide). For example, the compiler knows that, in iOS, the CGColor returned by the CGColor method of UIColor is not owned. The following methods therefore work as-is:

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        CAGradientLayer *gradientLayer = (CAGradientLayer *)[self layer];
        gradientLayer.colors = [NSArray arrayWithObjects:[[UIColor darkGrayColor] CGColor],
                                                         [[UIColor lightGrayColor] CGColor], nil];
        gradientLayer.startPoint = CGPointMake(0.0, 0.0);
        gradientLayer.endPoint = CGPointMake(1.0, 1.0);
    }
    return self;
}

Cast Function Parameters Using Ownership Keywords

When you cast between Objective-C and Core Foundation objects in function calls, you need to tell the compiler about the ownership semantics of the passed object. The ownership rules for Core Foundation objects are those specified in the Core Foundation memory management rules (see Memory Management Programming Guide for Core Foundation); rules for Objective-C objects are specified in Advanced Memory Management Programming Guide.

In the following code fragment, the array passed to the CGGradientCreateWithColors function requires an appropriate cast. Ownership of the object returned by arrayWithObjects: is not passed to the function, thus the cast is __bridge.

NSArray *colors = [NSArray arrayWithObjects:[[UIColor darkGrayColor] CGColor],
                                            [[UIColor lightGrayColor] CGColor], nil];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);

The code fragment is shown in context in the following method implementation. Notice also the use of Core Foundation memory management functions where dictated by the Core Foundation memory management rules.

- (void)drawRect:(CGRect)rect {
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGFloat locations[2] = {0.0, 1.0};
    NSArray *colors = [NSArray arrayWithObjects:[[UIColor darkGrayColor] CGColor],
                                                [[UIColor lightGrayColor] CGColor], nil];
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);
    CGColorSpaceRelease(colorSpace);  // Release owned Core Foundation object.
    CGPoint startPoint = CGPointMake(0.0, 0.0);
    CGPoint endPoint = CGPointMake(CGRectGetMaxX(self.bounds), CGRectGetMaxY(self.bounds));
    CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint,
                                kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    CGGradientRelease(gradient);  // Release owned Core Foundation object.
}

Common Issues While Converting a Project

When migrating existing projects, you are likely to run into various issues. Here are some common issues, together with solutions.

You can’t invoke retain, release, or autorelease.

This is a feature. You also can’t write:

while ([x retainCount]) { [x release]; }
You can’t invoke dealloc.

You typically invoke dealloc if you are implementing a singleton or replacing an object in an init methods. For singletons, use the shared instance pattern. In init methods, you don't have to call dealloc anymore, because the object will be freed when you overwrite self.

You can’t use NSAutoreleasePool objects.

Use the new @autoreleasepool{} construct instead. This forces a block structure on your autorelease pool, and is about six times faster than NSAutoreleasePool. @autoreleasepool even works in non-ARC code. Because @autoreleasepool is so much faster than NSAutoreleasePool, many old “performance hacks” can simply be replaced with unconditional @autoreleasepool.

The migrator handles simple uses of NSAutoreleasePool, but it can't handle complex conditional cases, or cases where a variable is defined inside the body of the new @autoreleasepool and used after it.

ARC requires you to assign the result of [super init] to self in init methods.

The following is invalid in ARC init methods:

[super init];

The simple fix is to change it to:

self = [super init];

The proper fix is to do that, and check the result for nil before continuing:

self = [super init];
if (self) {
   ...
You can’t implement custom retain or release methods.

Implementing custom retain or release methods breaks weak pointers. There are several common reasons for wanting to provide custom implementations:

  • Performance.

    Please don’t do this any more; the implementation of retain and release for NSObject is much faster now. If you still find problems, please file bugs.

  • To implement a custom weak pointer system.

    Use __weak instead.

  • To implement singleton class.

    Use the shared instance pattern instead. Alternatively, use class instead of instance methods, which avoids having to allocate the object at all.

If you you find that you must implement custom retain or release methods, then you must also implement the following method in your class:

-(BOOL)supportsWeakPointers { return NO; }

This method will prevent weak pointers from being formed to your objects. You are strongly encouraged to find a solution that doesn’t require implementing your own retain and release methods instead of doing this.

You can't use strong ids in C structures.

For example, the following code won’t compile:

struct X { id x; float y; };

This is because x defaults to strongly retained and the compiler can’t safely synthesize all the code required to make it work correctly. For example, if you pass a pointer to one of these structures through some code that ends up doing a free, each id would have to be released before the struct is freed. The compiler cannot reliably do this, so strong ids in structures are disallowed completely in ARC mode. There are a few possible solutions:

  1. Use Objective-C objects instead of structs.

    This is considered to be best practice anyway.

  2. If using Objective-C objects is sub-optimal, (maybe you want a dense array of these structs) then consider using a void* instead.

    This requires the use of the explicit casts, described below.

  3. Mark the object reference as __unsafe_unretained.

    This approach may be useful for the semi-common patterns like this:

    struct x { NSString *S;  int X; } StaticArray[] = {
      @"foo", 42,
      @"bar, 97,
    ...
    };

    You declare the structure as:

    struct x { __unsafe_unretained NSString *S; int X; }

    This may be problematic and is unsafe if the object could be released out from under the pointer, but it is very useful for things that are known to be around forever like constant string literals.

You can’t directly cast between id and void* (including Core Foundation types).

This is discussed in greater detail in “Managing Toll-Free Bridging”.

Frequently Asked Questions

How do I think about ARC? Where does it put the retains/releases?

Try to stop thinking about where the retain/release calls are put and think about your application algorithms instead. Think about “strong and weak” pointers in your objects, about object ownership, and about possible retain cycles.

Do I still need to write dealloc methods for my objects?

Maybe.

Because ARC does not automate malloc/free, management of the lifetime of Core Foundation objects, file descriptors, and so on, you still free such resources by writing a dealloc method.

You do not have to (indeed cannot) release instance variables, but you may need to invoke [self setDelegate:nil] on system classes and other code that isn’t compiled using ARC.

dealloc methods in ARC do not require—or allow—a call to [super dealloc]; the chaining to super is handled and enforced by the runtime.

Are retain cycles still possible in ARC?

Yes.

ARC automates retain/release, and inherits the issue of retain cycles. Fortunately, code migrated to ARC rarely starts leaking, because properties already declare whether the properties are retaining or not.

How do blocks work in ARC?

Blocks “just work” when you pass blocks up the stack in ARC mode, such as in a return. You don’t have to call Block Copy any more. You still need to use [^{} copy] when passing “down” the stack into arrayWithObjects: and other methods that do a retain.

The one thing to be aware of is that __block NSString *S" is retained in ARC mode, not a possibly dangling pointer. To get the previous behavior, use __block __unsafe_unretained NSString *S or (better still) use __block __weak NSString *S.

Can I develop applications for Mac OS X with ARC using Snow Leopard?

No. The Snow Leopard version of Xcode 4.2 doesn’t support ARC at all on Mac OS X, because it doesn’t include the 10.7 SDK. Xcode 4.2 for Snow Leopard does support ARC for iOS though, and Xcode 4.2 for Lion supports both Mac OS X and iOS. This means you need a Lion system to build an ARC application that runs on Snow Leopard.

Can I create a C array of retained pointers under ARC?

Yes, you can, as illustrated by this example:

// Note calloc() to get zero-filled memory.
__strong SomeClass **dynamicArray = (__strong SomeClass **)calloc(sizeof(SomeClass *), entries);
for (int i = 0; i < entries; i++) {
     dynamicArray[i] = [[SomeClass alloc] init];
}
 
// When you're done, set each entry to nil to tell ARC to release the object.
for (int i = 0; i < entries; i++) {
     dynamicArray[i] = nil;
}
free(dynamicArray);

There are a number of aspects to note:

  • You will need to write __strong SomeClass ** in some cases, because the default is __autoreleasing SomeClass **.

  • The allocated memory must be zero-filled.

  • You must set each element to nil before freeing the array (memset or bzero will not work).

  • You should avoid memcpy or realloc.

Is ARC slow?

It depends on what you’re measuring, but generally “no.” The compiler efficiently eliminates many extraneous retain/release calls and much effort has been invested in speeding up the Objective-C runtime in general. In particular, the common “return a retain/autoreleased object” pattern is much faster and does not actually put the object into the autorelease pool, when the caller of the method is ARC code.

One issue to be aware of is that the optimizer is not run in common debug configurations, so expect to see a lot more retain/release traffic at -O0 than at -Os.

Does ARC work in ObjC++ mode?

Yes. You can even put strong/weak ids in classes and containers. The ARC compiler synthesizes retain/release logic in copy constructors and destructors etc to make this work. One thing to be aware of is that you have to explicitly qualify some pointers with __strong, for example:

std::vector<__strong NSString*> V;

Which classes don’t support zeroing-weak references?

You cannot currently create zeroing-weak references to instances of the following classes:

NSATSTypesetter, NSColorSpace, NSFont, NSFontManager, NSFontPanel, NSImage, NSMenuView, NSParagraphStyle, NSSimpleHorizontalTypesetter, NSTableCellView, NSTextView, NSViewController, NSWindow, and NSWindowController. In addition, in OS X no classes in the AV Foundation framework support weak references.

For declared properties, you should use assign instead of weak; for variables you should use __unsafe_unretained instead of __weak.

In addition, you cannot create weak references from instances of NSHashTable, NSMapTable, or NSPointerArray under ARC.

What do I have to do when subclassing NSCell or another class that uses NSCopyObject?

Nothing special. ARC takes care of cases where you had to previously add extra retains explicitly. With ARC, all copy methods should just copy over the instance variables.

Can I opt out of ARC for specific files?

Yes.

When you migrate a project to use ARC, the -fobjc-arc compiler flag is set as the default for all Objective-C source files. You can disable ARC for a specific class using the -fno-objc-arc compiler flag for that class. In Xcode, in the target Build Phases tab, open the Compile Sources group to reveal the source file list. Double-click the file for which you want to set the flag, enter -fno-objc-arc in the pop-up panel, then click Done.

image: Art/fno-objc-arc.png

Is GC (Garbage Collection) deprecated on the Mac?

GC remains an option for development in Mac OS X v10.7. You are strongly encouraged to consider ARC for new development. For existing codebases (both manual reference counting and GC), you are encouraged to “test the waters.” This is, however, a non-zero amount of work and you should weigh that effort with your other priorities.


智能体式AI漫游指南中文版 智能体式AI漫游指南中文版、智能体式AI指南英文原版 立即下载

相关推荐

YOLO26算法星形目标识别+训练好的模型+100张数据集+pyqt可视化界面.zip

附训练好的 YOLO 权重与 PyQt 可视化检测界面,页面底部含可视化效果预览,毕设/课设开箱即用。 【数据集概况】 · 检测类别(中文):[星星(Star)] 【训练曲线与评估图】 【模型训练配置】 参数 | 值 模型 | yolo26n 训练轮数 | 100 epochs 输入尺寸 | 640x640 批次大小 | 24 优化器 | auto 初始学习率 | 0.01 训练设备 【关键指标汇总】 训练了 85 个 epoch,最终轮指标: 指标 | 数值 mAP50 | **0.9950** mAP50-95 | 0.8477 Precision | 1.0000 Recall | 0.9954 train/box_loss | 0.8235 train/cls_loss | 0.7275 val/box_loss | 0.7248 val/cls_loss | 0.9621 【训练过程分析】 85 轮训练后,我们得到了一个 mAP50 为 0.9950 的模型,这真是让人惊喜的成绩。一开始,模型的训练过程进展非常迅速,loss 在前 20 轮内从 1.5000 下降到 1.0000 附近,此后,loss 依然保持稳步下降,但速度明显放缓,特别是在第 30 轮到第 50 轮之间,loss 曲线进入了一个平台期,大约在 0.85 附近徘徊了 10 轮,直到第 60 轮左右才再度加速下降。这样的表现说明模型在前期阶段收敛良好,但到了后期,确实需要更多的训练轮次以确保模型的稳定性。 在验证集上,val_loss 保持平稳,没有出现明显的波动,这进一步证明了模型没有过拟合。然而,我们注意到在第 80 轮和第 85 轮之间,val_loss 似乎有所微弱的反弹,尽管这种波动并不显著。在训练集上,前 50 轮训... 使用场景:毕业设计、课程设计、深度学习入门、工业场景落地验证。

[翻译]Transitioning to ARC Release Notes中文版

http://transideology.com/2015/09/%E7%BF%BB%E8%AF%91transitioning-to-arc-release-notes/ 模式下运行。鉴于 @autoreleasepool 比 NSAutoreleasePool 快如此之多,一些老的性能优化小技巧可以被简单的替换成 @autoreleasepool方式了。 转换器可以处理

leonpengweicn的专栏 555

国央企如何利用AI工具提升科技创新项目管理与成果转化能力?.docx

国央企如何利用AI工具提升科技创新项目管理与成果转化能力?

ios 迁移至ARC版本说明(Transitioning to ARC Release Notes)

摘要(Summary)         通过在编译期添加代码的方式,ARC保证所有对象按需存在,按需释放。从概念上来讲,它与手动引用计数(参见 Advanced Memory Management Programming Guide)有着相同的内存管理约定,二者都会为你添加合适的内存管理方法调用。         为了编译器能生成正确的代码,ARC限定了你可以使用的一些方法,以及t

Code-lover's Learning Notes 990

融合高斯扰动与竞争学习的改进型多目标部落竞争与成员合作算法(IMOCTCM)求解DTLZ1-DTLZ7及-盘式制动器设计研究(Matlab代码实现)

内容概要:本文档名为《Plecs全桥LLC谐振变换器仿真模型.txt》,但实际内容并非聚焦于该主题,而是一份涵盖多个科研领域的Matlab/Simulink仿真资源汇总清单。文档列举了包括多目标优化算法(如IMOCTCM、MOWAA)、电力电子变换器控制(如LLC谐振变换器、DAB变换器)、电机控制(如PMSM无感控制)、状态估计(如卡尔曼滤波)、微电网调度、无人机路径规划、图像处理、信号处理等多个方向的仿真研究课题,涉及Matlab、Python、Simulink、PSCAD等多种工具和编程语言。文档末尾频繁出现“完整资源下载:公众号——荔枝科研社”及百度网盘链接,表明其核心用途是推广和分享一系列科研仿真资料,服务于学术交流与资源共享。; 适合人群:适用于电气工程、自动化、控制科学与工程、电力系统、电子信息、机械电子、计算机科学等相关领域的研究生、科研人员及工程技术人员。; 使用场景及目标:①为科研工作者提供丰富的Matlab/Simulink仿真案例参考和技术实现思路;②辅助高校师生完成课程设计、毕业设计或学术论文复现工作;③通过获取开源共享资源加速个人或团队的项目开发与算法验证进程。; 阅读建议:该文档属于资源目录性质,缺乏连贯的技术论述与逻辑结构,建议使用者根据自身研究方向筛选相关条目,结合提供的代码和模型进行学习与实践,并注意核实所下载资源的有效性、完整性以及代码运行环境的兼容性。

储能双向Buck-Boost+模型预测电流控制+电压下垂控制仿真【附参考文献】(Simulink仿真实现)

内容概要:本文档详细介绍了一套针对储能双向Buck-Boost变换器的Simulink仿真资源,融合模型预测电流控制与电压下垂控制策略,适用于微电网及分布式能源系统中的能量管理与稳定控制。仿真模型全面呈现了双向Buck-Boost电路在储能系统充放电过程中的动态行为,重点引入模型预测控制(MPC)与下垂控制相结合的先进控制算法,有效提升了系统的响应速度、稳定性与鲁棒性。文档不仅提供了完整的仿真模型结构与参数设置,还附有详实的参考文献,便于使用者深入理解控制原理并开展理论延伸研究,是电力电子、新能源系统等领域科研与教学的重要实践资料。; 适合人群:电气工程、自动化、新能源等相关专业的硕士博士研究生、科研人员以及从事电力电子变换器与微电网系统设计的工程师。; 使用场景及目标:①用于微电网中储能系统的建模与协调控制策略研究;②开展模型预测控制(MPC)与电压下垂控制在直流变换器中的联合应用仿真分析;③支撑高校电力电子课程实验、毕业设计及科研项目开发,深化对双向DC-DC变换器非线性特性和先进控制算法实现机制的理解。; 阅读建议:建议结合Simulink仿真模型与配套文档同步学习,重点关注控制器的设计逻辑、参数整定方法及系统动态响应特性,推荐对比传统PI控制与先进控制策略的仿真结果,以深入掌握不同控制方案的性能差异与优化路径。

迁移至ARC版本说明(Transitioning to ARC Release Notes)

为什么80%的码农都做不了架构师?>>> ...

weixin_34343689的博客 214

基于双向Buck-Boost电路的锂电池储能充电+放电控制Simulink仿真

内容概要:本文档围绕基于双向Buck-Boost电路的锂电池储能系统展开,详细介绍了其在充电与放电过程中的Simulink仿真设计与实现方法。通过构建双向Buck-Boost电路模型,结合模型预测电流控制与电压下垂控制策略,实现了对锂电池储能系统的高效能量管理与双向功率流动控制。文档提供了完整的仿真模型架构、控制算法设计流程、系统稳定性分析及动态响应性能验证,涵盖了从主电路建模到闭环控制参数整定的关键环节,适用于储能系统中能量双向变换的科研与工程实践。; 适合人群:具备电力电子、自动控制理论及新能源系统基础知识的高校研究生、科研人员以及从事储能系统、微电网、电动汽车等领域技术研发的工程技术人员。; 使用场景及目标:①用于锂电池储能系统的教学实验与科研仿真研究;②支撑微电网、电动汽车、V2G(Vehicle-to-Grid)等应用场景中的能量双向变换与功率调度研究;③深入理解Buck-Boost电路的工作原理及其在实际系统中的先进控制策略实现机制。; 阅读建议:建议在Simulink环境中实际搭建并调试所提供的仿真模型,重点关注控制环路的设计逻辑与参数整定过程,结合文中引用的参考文献深化对系统建模、控制理论与工程应用之间关系的理解。

基于透镜天线阵列的毫米波大规模多输入多输出(MIMO)系统可靠波束空间信道估计研究(Matlab代码实现)

内容概要:本文围绕Plecs环境下全桥LLC谐振变换器的仿真模型展开研究,系统阐述了其在电力电子系统中的建模方法、控制策略及动态性能分析。文章详细介绍了LLC谐振变换器的工作原理与典型拓扑结构,基于Plecs仿真平台构建了高精度的系统模型,并对谐振参数设计、软开关实现条件、变频控制策略等关键技术进行了深入的仿真验证。研究进一步探讨了系统在不同负载与输入电压条件下的效率特性、动态响应及稳定性表现,充分展示了LLC变换器在实现高效率、高功率密度电源变换方面的显著优势和应用价值。; 适合人群:具备电力电子与电力系统基础知识,从事开关电源、新能源变换器设计、仿真与控制的研究生、工程师及科研人员。; 使用场景及目标:①作为全桥LLC谐振变换器的仿真教学与科研验证平台;②指导实际工程中LLC变换器的谐振腔参数设计与控制环路优化;③支撑高频高效AC-DC或DC-DC电源系统的开发与综合性能评估。; 阅读建议:建议读者结合Plecs软件动手实践,重点关注谐振参数设计与变频控制环路调试部分,通过对比仿真结果深入理解变换器的软开关实现机理、负载适应性及效率优化方法。

PSIM-三相维也纳VIENNA整流器电压电流双闭环+中点电位平衡SVPWM控制仿真

内容概要:本文档围绕基于PSIM软件实现的三相维也纳(VIENNA)整流器展开,重点研究其电压电流双闭环控制系统与中点电位平衡控制策略。该仿真模型面向高效率、高功率因数的应用场景,详细构建了维也纳整流器的主电路结构及控制架构,涵盖电压外环与电流内环的双闭环PI控制器设计,以确保系统具备优良的动态响应与稳态性能。针对三电平拓扑中存在的中点电压偏移问题,引入空间矢量脉宽调制(SVPWM)技术进行优化调控,有效抑制中点电位波动,提升输出电压质量和系统运行稳定性。文档还配套提供了Mathcad计算书、仿真模型及相关参考资料,便于读者开展参数设计、控制逻辑分析与仿真复现工作。; 适合人群:电力电子、电气工程及其自动化等相关专业的研究生、科研人员,以及从事新能源变换器、工业电源、电动汽车充电设施等领域的研发工程师和技术人员。; 使用场景及目标:①深入理解三相三电平维也纳整流器的工作原理与数学建模方法;②掌握电压电流双闭环控制系统的结构设计与PI参数整定技巧;③学习SVPWM在中点电位平衡控制中的实现机制与调制策略;④为高功率密度PFC整流器、充电桩前端电路、航空航天电源等高端电力电子装置的研发提供仿真验证平台与技术支撑。; 阅读建议:建议结合PSIM仿真环境动手实践,利用所提供的计算书和参考文献,重点剖析双闭环控制环路的动态特性与SVPWM调制逻辑,并通过改变负载条件、输入电压或系统参数等方式测试系统的鲁棒性与控制有效性,进一步深化对控制策略的理解与工程应用能力。

硅纪元应用测评 | AI搜索引擎大比拼:360AI搜索、秘塔搜索、GenSpark AI和天工AI对比评测

搜索引擎输出的每个段落都有对应的出处,如果有错误,也是信息源的问题,从普通用户的角度来看,这与AI搜索的产品关系不大,能让用户对AI搜索的服务和得到的信息有一个隔离。同时,提供更多的定制选项,允许用户根据自己的偏好调整搜索结果的权重和排序,将使得搜索体验更加个性化和满足用户的具体需求。此外,大部分搜索工具还提供了一个无广告的搜索环境(360AI搜索部分内容会有广告),极大地提升了用户的搜索体验。AI搜索的本质依然是搜索,但它通过AI的逻辑分析和语言重新组织,使用户能够快速得到想要的信息。

guijiyuantech的博客 2013
上一篇: 图解苹果iOS 5的24个秘密功能(图)
下一篇: iOS5编程--官方例子代码研究--6.MailComposer
NickTang
博客等级 码龄24年 261粉丝 49原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值