当前位置:  编程技术>移动开发
本页文章导读:
    ▪几个Info系列的种的总结        几个Info系列的类的总结   首先我们来看一下PackageItemInfo,它是包含了一些信息的基类,它的直接子类有:ApplicationInfo、ComponentInfo、InstrumentationInfo、PermissionGroupInfo、PermissionInfo。它的间接子.........
    ▪ Ant 惯用任务        Ant 常用任务 写道 Ant 常用任务1 property 任务:用法:<property file="${basedir}/comversion.properties" />在构建文件中引入属性文件中的属性,以后直接用${key} 即可。2 ant 任务:用法:调用buildcompon.........
    ▪ object-c 对象内存储器分配情况       object-c 对象内存分配情况 最近在翻 《iphone开发秘籍》第二版 这本书,发现还是挺不错的,很多细节的问题都介绍的比较清楚。 不过刚看到第三章的时候,有个“内存分配” 的小节,里面有个.........

[1]几个Info系列的种的总结
    来源: 互联网  发布时间: 2014-02-18
几个Info系列的类的总结
 

首先我们来看一下PackageItemInfo,它是包含了一些信息的基类,它的直接子类有:ApplicationInfo、ComponentInfo、InstrumentationInfo、PermissionGroupInfo、PermissionInfo。它的间接子类有:ActivityInfo、ProviderInfo、ServiceInfo。这个类包含的信息对于所有包中项目是平等的。

public class PackageItemInfo extends Object
java.lang.Object    ↳ android.content.pm.PackageItemInfo Known Direct Subclasses
ApplicationInfo, ComponentInfo, InstrumentationInfo, PermissionGroupInfo, PermissionInfo
Known Indirect Subclasses
ActivityInfo, ProviderInfo, ServiceInfo
 
这些Package items是被Package manager所持有的。这个类提供了属性的非常普通的基本设置:label、icon和meta-data。这个类的意图不是被自己调用。它在这只是简单地分享被package manager返回的所有items之间的普通定义。比如,它自己并不实现Parcelable接口,但却帮助实现了Parcelable的子类提供了方便的方法。

   ApplicationInfo是从一个特定的应用得到的信息。这些信息是从相对应的Androdimanifest.xml的<application>标签中收集到的。

   ResolveInfo这个类是通过解析一个与IntentFilter相对应的intent得到的信息。它部分地对应于从AndroidManifest.xml的<intent>标签收集到的信息。

  PackageManager这个类是用来返回各种的关联了当前已装入设备了的应用的包的信息。你可以通过getPacageManager来得到这个类。

  ApplicationInfo与ResolveInfo比较:前者能够得到Icon、Label、meta-data、description。后者只能得到Icon、Label。

  下面讲一下这几个类综合在一起的具体应用:

  通过调用PackageManager的方法可以得到两种不同的信息:

  首先要得到manager:

PackageManager manager = getPackageManager();

  方法一:

List<ApplicationInfo> appList = manager.getInstalledApplications(PackageManager.GET.UNINSTALLED_PAKAGES);

  它是通过解析AndroidManifest.xml的<application>标签中得到的,所以它能得到所有的app。

  方法二:

Intent intent = new Intent(Intent.A CTION_MAIN,null);

intent.addCategory(Intent.CATEGORY_LAUNCHER);

List<ResolveInfo> appList = manager.queryIntentActivities(intent,0);

  它是通过解析<Intent-filter>标签得到有

<action android:name=”android.intent.action.MAIN”/>

<action android:name=”android.intent.category.LAUNCHER”/>

  这样的app,所以得到的要比第一种方法少(前者比它多那种service、previder等app)

 

public class PackageInfo extends Object
implements Parcelable
java.lang.Object    ↳ android.content.pm.PackageInfo
Fields public ActivityInfo[] activities  Array of all <activity> tags included under <application>, or null if there were none. public ApplicationInfo

applicationInfo 

应用程序

Information collected from the <application> tag, or null if there was none. public ConfigurationInfo[] configPreferences Application specified preferred configuration <uses-configuration> tags included under <manifest>, or null if there were none. public int[] gids All kernel group-IDs that have been assigned to this package. public InstrumentationInfo[] instrumentation Array of all <instrumentation> tags included under <manifest>, or null if there were none. public String packageName  包名 The name of this package. public PermissionInfo[] permissions Array of all <permission> tags included under <manifest>, or null if there were none. public ProviderInfo[] providers Array of all <provider> tags included under <application>, or null if there were none. public ActivityInfo[] receivers Array of all <receiver> tags included under <application>, or null if there were none. public FeatureInfo[] reqFeatures The features that this application has said it requires. public String[] requestedPermissions Array of all <uses-permission> tags included under <manifest>, or null if there were none. public ServiceInfo[] services Array of all <service> tags included under <application>, or null if there were none. public String sharedUserId The shared user ID name of this package, as specified by the <manifest> tag's sharedUserId attribute. public int sharedUserLabel The shared user ID label of this package, as specified by the <manifest> tag's sharedUserLabel attribute. public Signature[] signatures Array of all signatures read from the package file. public int versionCode   版本号 The version number of this package, as specified by the <manifest> tag's versionCode attribute. public String versionName 版本名 The version name of this package, as specified by the <manifest> tag's versionName attribute.

 

public class ApplicationInfo extends PackageItemInfo
implements Parcelable
java.lang.Object    ↳ android.content.pm.PackageItemInfo      ↳ android.content.pm.ApplicationInfo
 
public String backupAgentName Class implementing the Application's backup functionality. public String className Class implementing the Application object. public String dataDir Full path to a directory assigned to the package for its persistent data. public int descriptionRes A style resource identifier (in the package's resources) of the description of an application. public boolean enabled When false, indicates that all components within this application are considered disabled, regardless of their individually set enabled status. public int flags Flags associated with the application. public String manageSpaceActivityName Class implementing the Application's manage space functionality. public String permission Optional name of a permission required to be able to access this application's components. public String processName The name of the process this application should run in. public String publicSourceDir Full path to the location of the publicly available parts of this package (i.e. public String[] sharedLibraryFiles Paths to all shared libraries this application is linked against. public String sourceDir Full path to the location of this package. public int targetSdkVersion The minimum SDK version this application targets. public String taskAffinity Default task affinity of all activities in this application. public int theme A style resource identifier (in the package's resources) of the default visual theme of the application. public int uid The kernel user-ID that has been assigned to this application; currently this is not a unique ID (multiple applications can have the same uid).
Public Methods int describeContents()
Describe the kinds of special objects contained in this Parcelable's marshalled representation.
void dump(Printer pw, String prefix) CharSequence loadDescription(PackageManager pm)
Retrieve the textual description of the application.
String toString()
Returns a string containing a concise, human-readable description of this object.
void writeToParcel(Parcel dest, int parcelableFlags)

 

Inherited Methods
 From class android.content.pm.PackageItemInfo
void dumpBack(Printer pw, String prefix) void dumpFront(Printer pw, String prefix) Drawable loadIcon(PackageManager pm)
Retrieve the current graphical icon associated with this item.  加载图标
CharSequence loadLabel(PackageManager pm)
Retrieve the current textual label associated with this item. 加载标签名字
XmlResourceParser loadXmlMetaData(PackageManager pm, String name)
Load an XML resource attached to the meta-data of this item.
void writeToParcel(Parcel dest, int parcelableFlags)

 

 

public abstract class PackageManager extends Object
java.lang.Object    ↳ android.content.pm.PackageManager Known Direct Subclasses
MockPackageManager

 

 

Public Methods abstract void addPackageToPreferred(String packageName)
This method is deprecated. This function no longer does anything; it was an old approach to managing preferred activities, which has been superceeded (and conflicts with) the modern activity-based preferences.
abstract boolean addPermission(PermissionInfo info)
Add a new dynamic permission to the system.
abstract boolean addPermissionAsync(PermissionInfo info)
Like addPermission(PermissionInfo) but asynchronously persists the package manager state after returning from the call, allowing it to return quicker and batch a series of adds at the expense of no guarantee the added permission will be retained if the device is rebooted before it is written.
abstract void addPreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity)
This method is deprecated. This is a protected API that should not have been available to third party applications. It is the platform's responsibility for assigning preferred activities and this can not be directly modified. Add a new preferred activity mapping to the system. This will be used to automatically select the given activity component when Context.startActivity() finds multiple matching activities and also matches the given filter.
abstract String[] canonicalToCurrentPackageNames(String[] names)
Map from a packages canonical name to the current name in use on the device.
abstract int checkPermission(String permName, String pkgName)
Check whether a particular package has been granted a particular permission.
abstract int checkSignatures(String pkg1, String pkg2)
Compare the signatures of two packages to determine if the same signature appears in both of them.
abstract int checkSignatures(int uid1, int uid2)
Like checkSignatures(String, String), but takes UIDs of the two packages to be checked.
abstract void clearPackagePreferredActivities(String packageName)
Remove all preferred activity mappings, previously added with addPreferredActivity(IntentFilter, int, ComponentName[], ComponentName), from the system whose activities are implemented in the given package name.
abstract String[] currentToCanonicalPackageNames(String[] names)
Map from the current package names in use on the device to whatever the current canonical name of that package is.
abstract Drawable getActivityIcon(Intent intent)
Retrieve the icon associated with an Intent.
abstract Drawable getActivityIcon(ComponentName activityName)
Retrieve the icon associated with an activity.
abstract ActivityInfo getActivityInfo(ComponentName className, int flags)
Retrieve all of the information we know about a particular activity class.
abstract List<PermissionGroupInfo> getAllPermissionGroups(int flags)
Retrieve all of the known permission groups in the system.
abstract int getApplicationEnabledSetting(String packageName)
Return the the enabled setting for an application.
abstract Drawable getApplicationIcon(String packageName)
Retrieve the icon associated with an application.   获取程序图标
abstract Drawable getApplicationIcon(ApplicationInfo info)
Retrieve the icon associated with an application.
abstract ApplicationInfo getApplicationInfo(String packageName, int flags)
Retrieve all of the information we know about a particular package/application.
abstract CharSequence getApplicationLabel(ApplicationInfo info)
Return the label to use for this application.   获取程序描述
abstract int getComponentEnabledSetting(ComponentName componentName)
Return the the enabled setting for a package component (activity, receiver, service, provider).
abstract Drawable getDefaultActivityIcon()
Return the generic icon for an activity that is used when no specific icon is defined.
abstract Drawable getDrawable(String packageName, int resid, ApplicationInfo appInfo)
Retrieve an image from a package.
abstract List<ApplicationInfo> getInstalledApplications(int flags)
Return a List of all application packages that are installed on the device.  获取所有已安装程序信息
abstract List<PackageInfo> getInstalledPackages(int flags)
Return a List of all packages that are installed on the device.    获取所有已安装 程序的包信息
abstract String getInstallerPackageName(String packageName)
Retrieve the package name of the application that installed a package.
abstract InstrumentationInfo getInstrumentationInfo(ComponentName className, int flags)
Retrieve all of the information we know about a particular instrumentation class.
abstract Intent getLaunchIntentForPackage(String packageName)
Return a "good" intent to launch a front-door activity in a package, for use for example to implement an "open" button when browsing through packages.
abstract String getNameForUid(int uid)
Retrieve the official name associated with a user id.
PackageInfo getPackageArchiveInfo(String archiveFilePath, int flags)
Retrieve overall information about an application package defined in a package archive file
abstract int[] getPackageGids(String packageName)
Return an array of all of the secondary group-ids that have been assigned to a package.
abstract PackageInfo getPackageInfo(String packageName, int flags)
Retrieve overall information about an application package that is installed on the system.
abstract String[] getPackagesForUid(int uid)
Retrieve the names of all packages that are associated with a particular user id.
abstract PermissionGroupInfo getPermissionGroupInfo(String name, int flags)
Retrieve all of the information we know about a particular group of permissions.
abstract PermissionInfo getPermissionInfo(String name, int flags)
Retrieve all of the information we know about a particular permission.
abstract int getPreferredActivities(List<IntentFilter> outFilters, List<ComponentName> outActivities, String packageName)
Retrieve all preferred activities, previously added with addPreferredActivity(IntentFilter, int, ComponentName[], ComponentName), that are currently registered with the system.
abstract List<PackageInfo> getPreferredPackages(int flags)
Retrieve the list of all currently configured preferred packages.
abstract ActivityInfo getReceiverInfo(ComponentName className, int flags)
Retrieve all of the information we know about a particular receiver class.
abstract Resources getResourcesForActivity(ComponentName activityName)
Retrieve the resources associated with an activity.
abstract Resources getResourcesForApplication(ApplicationInfo app)
Retrieve the resources for an application.
abstract Resources getResourcesForApplication(String appPackageName)
Retrieve the resources associated with an application.
abstract ServiceInfo getServiceInfo(ComponentName className, int flags)
Retrieve all of the information we know about a particular service class.
abstract FeatureInfo[] getSystemAvailableFeatures()
Get a list of features that are available on the system.
abstract String[] getSystemSharedLibraryNames()
Get a list of shared libraries that are available on the system.
abstract CharSequence getText(String packageName, int resid, ApplicationInfo appInfo)
Retrieve text from a package.
abstract XmlResourceParser getXml(String packageName, int resid, ApplicationInfo appInfo)
Retrieve an XML file from a package.
abstract boolean hasSystemFeature(String name)
Check whether the given feature name is one of the available features as returned by getSystemAvailableFeatures().
abstract boolean isSafeMode()
Return whether the device has been booted into safe mode.
abstract List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags)
Retrieve all receivers that can handle a broadcast of the given intent.
abstract List<ProviderInfo> queryContentProviders(String processName, int uid, int flags)
Retrieve content provider information.
abstract List<InstrumentationInfo> queryInstrumentation(String targetPackage, int flags)
Retrieve information about available instrumentation code.
abstract List<ResolveInfo> queryIntentActivities(Intent intent, int flags)
Retrieve all activities that can be performed for the given intent.
abstract List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, Intent[] specifics, Intent intent, int flags)
Retrieve a set of activities that should be presented to the user as similar options.
abstract List<ResolveInfo> queryIntentServices(Intent intent, int flags)
Retrieve all services that can match the given intent.
abstract List<PermissionInfo> queryPermissionsByGroup(String group, int flags)
Query for all of the permissions associated with a particular group.
abstract void removePackageFromPreferred(String packageName)
This method is deprecated. This function no longer does anything; it was an old approach to managing preferred activities, which has been superceeded (and conflicts with) the modern activity-based preferences.
abstract void removePermission(String name)
Removes a permission that was previously added with addPermission(PermissionInfo).
abstract ResolveInfo resolveActivity(Intent intent, int flags)
Determine the best action to perform for a given Intent.
abstract ProviderInfo resolveContentProvider(String name, int flags)
Find a single content provider by its base path name.
abstract ResolveInfo resolveService(Intent intent, int flags)
Determine the best service to handle for a given Intent.
abstract void setApplicationEnabledSetting(String packageName, int newState, int flags)
Set the enabled setting for an application This setting will override any enabled state which may have been set by the application in its manifest.
abstract void setComponentEnabledSetting(ComponentName componentName, int newState, int flags)
Set the enabled setting for a package component (activity, receiver, service, provider).

 

 

获取已安装程序的名字、包名、版本和图标

FROM:http://www.androidsnippets.org/snippets/70/

 

Java代码 
  • class PInfo {    
  •     private String appname = "";    
  •     private String pname = "";    
  •     private String versionName = "";    
  •     private int versionCode = 0;    
  •     private Drawable icon;    
  •     private void prettyPrint() {    
  •         log(appname + "\t" + pname + "\t" + versionName + "\t" + versionCode + "\t");    
  •     }    
  • }    
  •     
  • private void listPackages() {    
  •     ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */    
  •     final int max = apps.size();    
  •     for (int i=0; i<max; i++) {    
  •         apps.get(i).prettyPrint();    
  •     }    
  • }    
  •     
  • private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {    
  •     ArrayList<PInfo> res = new ArrayList<PInfo>();            
  •     List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);    
  •     for(int i=0;i<packs.size();i++) {    
  •         PackageInfo p = packs.get(i);    
  •         if ((!getSysPackages) && (p.versionName == null)) {    
  •             continue ;    
  •         }    
  •         PInfo newInfo = new PInfo();    
  •         newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();    
  •         newInfo.pname = p.packageName;    
  •         newInfo.versionName = p.versionName;    
  •         newInfo.versionCode = p.versionCode;    
  •         newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());    
  •         res.add(newInfo);    
  •     }    
  •     return res;     
  • }    
  • 获取未安装的APK信息
    java代码 
  • /** 获取未安装的APK信息 
  •      * @param context 
  •      * @param archiveFilePath APK文件的路径。如:/sdcard/download/XX.apk 
  •      */  
  •     public void getUninatllApkInfo(Context context, String archiveFilePath){  
  •         PackageManager pm = context.getPackageManager();  
  •         PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES);  
  •         if(info != null){  
  •             ApplicationInfo appInfo = info.applicationInfo;  
  •             String appName = pm.getApplicationLabel(appInfo).toString();  
  •             String packageName = appInfo.packageName;  
  •             Drawable icon = pm.getApplicationIcon(appInfo);  
  •         }  
  •     }  
  •  

    据测试:无法获取未安装APK的图片。


        
    [2] Ant 惯用任务
        来源: 互联网  发布时间: 2014-02-18
    Ant 常用任务
    写道
    Ant 常用任务
    1 property 任务:
    用法:
    <property file="${basedir}/comversion.properties" />
    在构建文件中引入属性文件中的属性,以后直接用${key} 即可。

    2 ant 任务:
    用法:
    调用buildcomponent.xml 文件同的默认目标。
    <ant
    antfile="./${xpd.01.path}/buildcomponent.xml">
    <property name="fe.path" value="${xpd.01.path}" /> 传递属性给目标
    <property name="fe.version" value="${xpd.01.version}" />
    </ant>

    3 delete 任务:删除文件和路径
    用法:
    <delete dir="${fe.path}/../pl" /> 删除pl路径

    4 foreach 任务:循环功能,包含在ant的扩展包中
    声明:
    <taskdef name="foreach" classname="net.sf.antcontrib.logic.ForEach" /> 在build文件中引入foreach task。
    【注】:因为foreach 任务(task) 不是ant 核心包提供的,所以应该下载foreach的类包,添加到ant 类路径,并在build 文件中声明该任务。上面的taskdef 任务就完成了foreach的声明。

    用法:
    <foreach target="fe.source" param="fe.source.path" list="${fe.plugin.path}" delimiter=";">
    循环调用fe.source目标,循环的变量为fe.source.path,功能为:把list的值用delimiter分割,并把值循环赋值给param。









    5 if 任务:程序分支的作用
    声明:
    <taskdef name="if" classname="net.sf.antcontrib.logic.IfTask" /> 在build文件中引入if task
    用法:
    <if>
    <and> 判断条件1
    <equals arg1="${src.exit}" arg2="true" />
    <equals arg1="${MANIFEST.exit}" arg2="true" />
    </and>

    <then> 满足判断条件1执行
    <antcall target="jartarget">
    <param name="pluginroot" value="${pluginpath}" />
    </antcall>
    </then>

    <elseif> 不满足判断条件1
    <not> 判断条件2
    <equals arg1="${MANIFEST.exit}" arg2="true" />
    </not>

    <then> 满足判断条件2
    <echo message="No MANIFEST.MF file" />
    </then>
    </elseif>

    <else> 其他情况
    <echo message="No Src directory" />
    </else>
    </if>

    6 propertyregex 任务
    声明:
    <taskdef name="propertyregex" classname="net.sf.antcontrib.property.RegexTask" />
    用法:
    <propertyregex property="fe.name" input="${pluginsourcepath}" regexp="/.*" replace="" />
    完成属性的替换,即:把pluginsourcepath中的以"." 开始的部分,替换成" "。








    7 manifest 任务
    用法:
    <manifest
    file="${pluginroot.temp}/META-INF/MANIFEST.MF" mode="update">
    <attribute name="Bundle-SymbolicName" value="${pluginid}.source" />
    <attribute name="Eclipse-SourceBundle" value='${pluginid};
    version="${allversion}";roots:="."' />

    <attribute name="Bundle-Version" value="${allversion}" />
    <attribute name="Bundle-Name" value="non" />
    <attribute name="Bundle-ManifestVersion" value="2" />
    </manifest>

    8 jar 任务
    用法:
    <jar
    destfile="${release.plugin.path}/${pluginid}.source_${allversion}.jar"
    manifest="${pluginroot.temp}/META-INF/MANIFEST.MF">
    <fileset dir="${pluginroot}/src" />
    <!-- <fileset dir="${pluginroot}/schema" /> -->
    <fileset dir="${pluginroot}" includes="schema/**" />
    </jar>

    9 available 任务
    用法:
    <available file="${pluginpath}/src/" type="dir" property="src.exit" />
    当${pluginpath}/src/ 路径存在时,src.exit 将被赋值为真。

    10 replace 任务
    用法:
    <replace file="${release.feature.path}/feature.xml"
    token='"6.2.1.qualifier"'
    value='"6.2.1.${plugindateversion}"' />
    把文件feature.xml 中包含6.2.1.qualifier 字符串替换为6.2.1.${plugindateversion}。

     


        
    [3] object-c 对象内存储器分配情况
        来源: 互联网  发布时间: 2014-02-18
    object-c 对象内存分配情况

    最近在翻 《iphone开发秘籍》第二版 这本书,发现还是挺不错的,很多细节的问题都介绍的比较清楚。

    不过刚看到第三章的时候,有个“内存分配” 的小节,里面有个问题:

     

     

    NSObject *object = [[NSObject alloc]init];

    NSLog(@"object pointer: %ld\n",sizeof(object));

    NSLog(@"object itself: %ld\n",sizeof(*object));

     

     

     

    发现sizeof(*object)这个并不能编译通过,查了一下发现这个新版本是不支持sizeof(*object)这种方式的,只有老的版本才支持(具体看这里)

    可以用以下方式代替:

     

    #import <malloc/malloc.h>// ...NSLog(@"object itself:%d\n", malloc_size(object));

    或者查看这里

    编译通过之后,我又继续来探索他是如何分配内存

     

    首先根据书上的例子创建了一个Car的类

    代码如下:

     

    //  Car.h
    //  SizeOf
    //
    //  Created by jakend on 13-3-31.
    //  Copyright (c) 2013年 Huhuood. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    
    @interface Car : NSObject
    
    {
        NSString *make;
        NSString *model;
        int year;
    }
    
    - (void)setMake:(NSString *)aMake andModel:(NSString *)aModel andYear:(int) aYear;
    
    - (void)printCarInfo;
    
    - (int) year;
    
    @end

     

     

    //
    //  Car.m
    //  SizeOf
    //
    //  Created by jakend on 13-3-31.
    //  Copyright (c) 2013年 Huhuood. All rights reserved.
    //
    
    #import "Car.h"
    
    @implementation Car
    
    - (void)setMake:(NSString *)aMake andModel:(NSString *)aModel andYear:(int) aYear
    {
        make = aMake;
        model = aModel;
        year = aYear;
    }
    
    - (void)printCarInfo;
    {
        NSLog(@"make ===== %@, year ==== %d, model ==== %@", make, year, model);
        NSLog(@"make size:%ld, year size:%ld, model size:%ld", sizeof(make), sizeof(year), sizeof(model));
    }
    
    - (int) year
    {
        return year;
    }
    
    @end
    



     

     

    然后便是打印它这个类的大小:

     

        Car *car = [[Car alloc]init];
        [car setMake:@"make1" andModel:@"model1" andYear:15];
        [car printCarInfo];
        
        NSObject *object = [[NSObject alloc]init];
        
        NSLog(@"object pointer: %ld\n", sizeof(object));
        NSLog(@"object itself: %ld\n", malloc_size(object));
        NSLog(@"car pointer: %ld\n", sizeof(car));
        NSLog(@"car itself: %ld\n", malloc_size(car));



     


    结果为:

     

     

    2013-03-31 22:19:45.611 SizeOf[2984:c07] make ===== make1, year ==== 15, model ==== model1

    2013-03-31 22:19:45.612 SizeOf[2984:c07] make size:4, year size:4, model size:4

    2013-03-31 22:19:45.613 SizeOf[2984:c07] object pointer: 4

    2013-03-31 22:19:45.613 SizeOf[2984:c07] object itself: 16

    2013-03-31 22:19:45.614 SizeOf[2984:c07] car pointer: 4

    2013-03-31 22:19:45.614 SizeOf[2984:c07] car itself: 16

     

    
    

     

     

     

    我们发现创建一个NSObject的对象的为16字节, 创建Car对象也需要16个字节, 它们对象的指针(这样称呼可能不合理)都是4个字节,也就是说创建一个NSObject及其子类最少需要分配16字节的大小;而不管是NSString对象的指针 还是int 的大小都是4个字节。(书上说16字节 = 2个NSString指针大小8b+ 1个int大小4b +对象本身指针大小4b,但是为什么NSObject对象一开始就是16个字节???)

    那么我们来看看对象创建内存的大小是如何分配的呢???

    这里我们只创建了3个变量,那么我们创建4个变量,5个,或者更多会是怎么样?它的内存又是多少?

    很简单,我们多加几个变量就知道了,给Car.h 文件加上一个NSString类型新的变量,代码如下:

     

     

    //  Car.h
    //  SizeOf
    //
    //  Created by jakend on 13-3-31.
    //  Copyright (c) 2013年 Huhuood. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    
    @interface Car : NSObject
    
    {
        NSString *make;
        NSString *model;
        NSString *name;//新加的变量
        int year;
    }
    
    - (void)setMake:(NSString *)aMake andModel:(NSString *)aModel andYear:(int) aYear;
    
    - (void)printCarInfo;
    
    - (int) year;
    
    @end

     

     

    然后再打印:

     

    2013-03-31 22:31:30.681 SizeOf[3380:c07] make ===== make1, year ==== 15, model ==== model

    12013-03-31 22:31:30.682 SizeOf[3380:c07] make size:4, year size:4, model size:4

    2013-03-31 22:31:30.682 SizeOf[3380:c07] object pointer: 4

    2013-03-31 22:31:30.683 SizeOf[3380:c07] object itself: 16

    2013-03-31 22:31:30.683 SizeOf[3380:c07] car pointer: 4

    2013-03-31 22:31:30.683 SizeOf[3380:c07] car itself:32

     

    我们发现car的变量为32字节了!!! 我们这里仅仅加了一个变量而已,怎么不是20字节?怎么就变成32字节了?

     

    于是我又加上一个NSString *name1,发现还是32字节,加到第五个(总共是8个变量)的时候,发现是48字节了。原来它空间不够的时候是16字节加1次!!!看来书上讲得也不一定正确。

     

    通过此例子,发现有些问题还是需要自己多尝试才会得出正确的结论,而不要照着书上死记硬背。

    ps:csdn的编辑器不熟悉,格式搞了很久。。。发现选择了jav段居然不能用其他颜色值跟字体大小????

     

     

    
    

     


        
    最新技术文章:
    ▪Android开发之登录验证实例教程
    ▪Android开发之注册登录方法示例
    ▪Android获取手机SIM卡运营商信息的方法
    ▪Android实现将已发送的短信写入短信数据库的...
    ▪Android发送短信功能代码
    ▪Android根据电话号码获得联系人头像实例代码
    ▪Android中GPS定位的用法实例
    ▪Android实现退出时关闭所有Activity的方法
    ▪Android实现文件的分割和组装
    ▪Android录音应用实例教程
    ▪Android双击返回键退出程序的实现方法
    ▪Android实现侦听电池状态显示、电量及充电动...
    ▪Android获取当前已连接的wifi信号强度的方法
    ▪Android实现动态显示或隐藏密码输入框的内容
    ▪根据USER-AGENT判断手机类型并跳转到相应的app...
    ▪Android Touch事件分发过程详解
    ▪Android中实现为TextView添加多个可点击的文本
    ▪Android程序设计之AIDL实例详解
    ▪Android显式启动与隐式启动Activity的区别介绍
    ▪Android按钮单击事件的四种常用写法总结
    ▪Android消息处理机制Looper和Handler详解
    ▪Android实现Back功能代码片段总结
    ▪Android实用的代码片段 常用代码总结
    ▪Android实现弹出键盘的方法
    ▪Android中通过view方式获取当前Activity的屏幕截...
    ▪Android提高之自定义Menu(TabMenu)实现方法
    ▪Android提高之多方向抽屉实现方法
    ▪Android提高之MediaPlayer播放网络音频的实现方法...
    ▪Android提高之MediaPlayer播放网络视频的实现方法...
    ▪Android提高之手游转电视游戏的模拟操控
     


    站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3